<?php
/**
 * Created by PhpStorm.
 * User: von
 * Date: 2017/12/15
 * Time: 10:29
 */

namespace backend\controllers;


/*
 * 混合类的项目-增删改查
 */
use backend\models\PackageInitiationPlan;
use common\models\InstationMessage;
use common\models\Package;
use common\models\ProjectLock;
use common\models\ProjectLog;
use common\models\ProjectPaymentCollection;
use common\models\ProjectUpdateLog;
use common\models\Responses;
use common\models\User;
use yii;
use backend\models\Country;
use common\models\Project;
use common\models\ProjectTeam;
use backend\models\SearchPackage;
use common\models\ProjectLike;
use common\models\UserModel;
use yii\helpers\ArrayHelper;
use yii\data\Pagination;

class ProjectController extends BaseController
{
    /*单项目管理（ly）*/
    public function actionIndex()
    {
        //$data=Project::find()->with('package','team.user','provinceName','cityName');
        $pageSize=20;//默认每页显示条数
        $data = (new \yii\db\Query())
            ->from('project AS p')
            ->select('p.is_highlights,p.borrower,cp.title as province,cc.title as city,p.principal,p.is_suit,p.management_status,p.type2,pa.title,u.realname,p.guarantor,p.status,p.highlights,p.id,p.package_id')
            ->leftJoin('package AS pa', 'pa.id = p.package_id')
            ->leftJoin('project_team AS t', 't.project_id=p.id')
            ->leftJoin('user AS u', 'u.id=t.owner')
            ->leftJoin('country as cp', 'cp.id=p.province')
            ->leftJoin('country as cc', 'cc.id=p.city')->andWhere(['=','p.is_finished',1]);
        if (Yii::$app->request->isGet) {
            $getData = Yii::$app->request->get();
            if (isset($getData['keyWords']) && !empty($getData['keyWords'])) {//项目关键词
                $keyWords = trim($getData['keyWords']);
                $data->andWhere('p.title like "%' . $keyWords . '%" or p.borrower like "%' . $keyWords . '%" or pa.title like "%' . $keyWords . '%"');
            }
            if (isset($getData['is_highlights']) && !empty($getData['is_highlights'])) {//项目 显示亮点项目
                $data->andWhere(['=', 'p.is_highlights', $getData['is_highlights']]);
            }
            if (isset($getData['principal']) && $getData['principal'] >= 1) {//本金额度
                $principal = $getData['principal'];
                // $data->andWhere(['>','id',10])<option value="1">100万以下</option> option value="2">100-1000万</option> option value="3">1000-5000万</option><option value="4">5000-1 亿</option><option value="5">1 亿以上</option>
                switch ($principal) {
                    case 1:
                        $data->andWhere(['<=', 'p.principal', 1000000]);
                        break;
                    case 2:
                        $data->andWhere(['>', 'p.principal', 1000000])->andWhere(['<=', 'p.principal', 10000000]);
                        break;
                    case 3:
                        $data->andWhere(['>', 'p.principal', 10000000])->andWhere(['<=', 'p.principal', 50000000]);
                        break;
                    case 4:
                        $data->andWhere(['>', 'p.principal', 50000000])->andWhere(['<=', 'p.principal', 100000000]);
                        break;
                    case 5:
                        $data->andWhere(['>', 'p.principal', 100000000]);
                        break;
                }
            }
            if (isset($getData['mortgage_type']) && !empty($getData['mortgage_type'])) {//抵押物类型
                $data->andWhere(['like', 'p.mortgage_type', $getData['mortgage_type']]);
            }
            if (isset($getData['status']) && !empty($getData['status'])) {//项目状态
                $data->andWhere(['=', 'p.status', $getData['status']]);
            }
            if (isset($getData['type2']) && !empty($getData['type2'])) {//项目类型
                $data->andWhere(['=', 'p.type2', $getData['type2']]);
            }
            if (isset($getData['owner']) && trim($getData['owner'])) {//项目经理
                $ownerIds = array();
                $ownerId = UserModel::find()->select('id')->where(['like', 'realname', trim($getData['owner'])])->asArray()->all();
                if (count($ownerId) > 0) {
                    foreach ($ownerId as $userId) {
                        $ownerIds[] = $userId['id'];
                    }
                    //添加搜素单项目的项目中的条件
                    $data->andWhere(['in', 't.owner', $ownerIds]);
                }
            }
            if (isset($getData['province']) && !empty($getData['province'])) {//项目省
                $data->andWhere(['=', 'p.province', $getData['province']]);
            }
            if (isset($getData['city']) && !empty($getData['city'])) {//项目市
                $data->andWhere(['=', 'p.city', $getData['city']]);
            }
            if (isset($getData['manager']) && trim($getData['manager'])) {//项目总监
                $managerIds = array();
                $managerId = UserModel::find()->select('id')->where(['like', 'realname', trim($getData['manager'])])->asArray()->all();
                if (count($managerId) > 0) {
                    foreach ($managerId as $userId) {
                        $managerIds[] = $userId['id'];
                    }
                    //添加搜素单项目的项目中的条件
                    $data->andWhere(['in', 't.manager', $managerIds]);
                }
            }
            if (isset($getData['partner']) && trim($getData['partner'])) {//项目团队成员
                $partnerIdsStr = '';
                $partnerId = UserModel::find()->select('id')->where(['like', 'realname', trim($getData['partner'])])->asArray()->all();
                if (count($partnerId) > 0) {
                    foreach ($partnerId as $userId) {//添加搜素单项目的项目中的条件$userId['id'];
                        if (!empty($partnerIdsStr)) $partnerIdsStr .= 'or';
                        $partnerIdsStr .= ' t.partner like "%,' . $userId['id'] . ',%"';
                    }
                    $data->andWhere($partnerIdsStr);
                }
            }
            if (isset($getData['is_suit'])&& $getData['is_suit']!='') {//诉讼状态&& $getData['is_suit'] >= 0
                $data->andWhere(['=', 'p.is_suit', intval($getData['is_suit'])]);
            }
            if(isset($getData['sort']) && $getData['sort']!=''){//排序
                $frist = substr($getData['sort'], 0, 1 );
                $sortName=str_replace('-','',$getData['sort']);
                switch ($sortName)
                {
                    case 'title'://资产包名称
                        $sortName='pa.'.$sortName;
                        break;
                    case 'realname'://项目经理
                        $sortName='u.'.$sortName;
                        break;
                    default:
                        $sortName='p.'.$sortName;
                }
                if($frist=='-'){//降序
                    $data->orderBy($sortName.' DESC');
                }else{//升
                    $data->orderBy($sortName.' ASC');
                }
            }else{//默认排序
                $data->orderBy('p.is_highlights ASC,p.id desc');
            }
            if(isset($getData['per-page']) && $getData['per-page']>0){
                $pageSize=intval($getData['per-page']);
            }
        }
//        $data->orderBy('p.is_highlights ASC,p.id desc');
        //获取项目总监manager  项目经理owner  团队成员partner 联想数据
        $user_array=UserModel::find()->select('realname')->all();
        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $pageSize]);    //$pageSize实例化分页类,带上参数(总条数,每页显示条数)
        $data_array = $data->offset($pages->offset)->limit($pages->limit)->all();//->asArray()->all()
        return $this->render('index', ['pages' => $pages, 'data' => $data_array,'users'=>$user_array]);
    }

    /*单项目 下载尽调报告 （ly）*/
    public function actionProjectDownLoad()
    {
        //projectid
        if (Yii::$app->request->isGet && Yii::$app->request->get('projectid') > 0) {
            $projectId = Yii::$app->request->get('projectid');
            $projectDetail = Project::find()->with('investigation', 'stakeholder.investigationLawsuit', 'investigationFile')->where(['id' => $projectId])->asArray()->all();
            //var_dump($projectDetail);exit;
            //添加项目操作日志-开始
            $projectLog = new ProjectLog();
            $projectLog->project_id = $projectId;
            $projectLog->created_at = date('Y-m-d H:i:s', time());
            $projectLog->user_id = Yii::$app->user->id;
            $projectLog->log = '下载尽调报告';
            $projectLog->save();
//            if (!$projectLog->save()) {
//                throw new Exception('项目操作日志保存失败');
//            }
            //添加项目操作日志-结束
            return $this->renderPartial('down-load-report', ['data' => $projectDetail[0]]);

        }
    }

    /*
     * 异步添加/更新项目字段
     * //1.基础信息
     */
    public function actionAjaxSaveBaseProject()
    {
        $Gdata = \Yii::$app->request->post('data');          //项目id
        $data = [];
        $project_id = !empty($Gdata['project_id']) ? $Gdata['project_id'] : 1;          //项目id
        $data['Id'] = !empty($Gdata['project_id']) ? $Gdata['project_id'] : 1;          //项目id
        $data['package_id'] = !empty($Gdata['package_id']) ? $Gdata['package_id'] : 33;          //项目id
        $data['Title'] = !empty($Gdata['title']) ? $Gdata['title'] : '';      //项目标题
        $data['Code'] = !empty($Gdata['code']) ? $Gdata['code'] : '';       //项目编号
        $data['Category'] = !empty($Gdata['projeactType']) ? $Gdata['projeactType'] : '';   //项目类型//1保证类、2抵押类、3混合类
        $data['Province'] = !empty($Gdata['province']) ? $Gdata['province'] : 0; //省份
        $data['City'] = !empty($Gdata['city']) ? $Gdata['city'] : 0; //城市
        $data['borrower'] = !empty($Gdata['borrowerName']) ? $Gdata['borrowerName'] : '';  //借款人
        $data['borrowerState'] = !empty($Gdata['borrowerStatus']) ? $Gdata['borrowerStatus'] : 0; //借款人状态
        $data['enterprise'] = !empty($Gdata['enterprise']) ? intval($Gdata['enterprise']) : 1;//企业类型
        $data['industry'] = !empty($Gdata['industry']) ? $Gdata['industry'] : ''; //所属行业
        $data['guarantor'] = !empty($Gdata['guarantor']) ? $Gdata['guarantor'] : ''; //保证人
        $data['guarantor_status'] = !empty($Gdata['guarantorState']) ? $Gdata['guarantorState'] : '';//保证人经营状况'//存续、吊销、注销、破产等同上
        $data['warranty'] = !empty($Gdata['warranty']) ? $Gdata['warranty'] : ''; //担保方式
        $data['principal'] = !empty($Gdata['principal']) ? str_replace(',','',$Gdata['principal']) : 1; //本金（元)
        $data['interest'] = !empty($Gdata['interest']) ?  str_replace(',','',$Gdata['interest']) : 1;    //利息（元)
        $data['prin_inter'] = !empty($Gdata['benxi']) ? $Gdata['benxi'] : 1;; //本息和                  //本息和
        $data['is_suit'] = !empty($Gdata['is_suit']) ? intval($Gdata['is_suit']) : 0;//诉讼状态
        $data['highlights'] = !empty($Gdata['highlights']) ? $Gdata['highlights'] : ''; //亮点明细
        $data['mortgage_details'] = !empty($Gdata['mortgage_details']) ? $Gdata['mortgage_details'] : ''; //抵押物详情描述
        $data['mortgage_type'] = !empty($Gdata['mortgage_type']) ? $Gdata['mortgage_type'] : ''; //抵押物类型
        $stateData = Project::saveBaseData($data);
        if ($stateData['code'] == 200) {
            //---编辑资产包-发送消息--fly---
            self::actionPostMessage($project_id);
            //---编辑资产包-发送消息--fly---

            $tableModel = "common\models\Project";
            $projectUnlock = ProjectLock::Unlock($tableModel, $project_id, 'id');
            if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                return json_encode(Responses::response200('', 1, '保存成功'));
            } else {
                return json_encode(Responses::response400($projectUnlock['message']));
            }
        }
        return false;
    }

    /*
    * 异步添加/更新项目字段
    * //1.司法进展信息
    */
    public function actionAjaxSaveLawsuitProject()
    {
        $Pdata = \Yii::$app->request->post('data');          //项目id
        $data = [];
        $project_id = !empty($Pdata['project_id']) ? $Pdata['project_id'] : 1;
        $data['Id'] = !empty($Pdata['project_id']) ? $Pdata['project_id'] : 1;          //项目id
        $data['judgement'] = !empty($Pdata['judgement']) ? $Pdata['judgement'] : '';          //判   决
        $data['execution'] = !empty($Pdata['execution']) ? $Pdata['execution'] : '';          //执   行
        $data['court'] = !empty($Pdata['court']) ? $Pdata['court'] : '';          //法院
        $data['block'] = !empty($Pdata['block']) ? $Pdata['block'] : '';          //列失信
        $params['project_id'] = $data['Id'];
        $stateData = Project::saveProjectPreEvaluationLawsuit($params, $data);
        if ($stateData['code'] == 200) {
            //---编辑资产包-发送消息--fly---
            self::actionPostMessage($project_id);
            //---编辑资产包-发送消息--fly---
            $tableModel = "common\models\ProjectPreEvaluationLawsuit";
            $projectUnlock = ProjectLock::Unlock($tableModel, $project_id, 'project_id');
            if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                return json_encode(Responses::response200('', 1, '保存成功'));
            } else {
                return json_encode(Responses::response400($projectUnlock['message']));
            }
        }
        return false;
    }

    /*
* 异步添加/更新项目字段
* //1.价值评估
     *
*/
    public function actionAjaxSaveEvaluationProject()
    {
        $Pdata = \Yii::$app->request->post('data');          //项目id
        $data = [];
        $project_id = !empty($Pdata['project_id']) ? $Pdata['project_id'] : 1;
        $data['Id'] = !empty($Pdata['project_id']) ? $Pdata['project_id'] : 1;          //项目id
        $data['reference'] = !empty($Pdata['reference']) ? str_replace(',','',$Pdata['reference']) : '';          //参考资产市场价值
        $data['conservation'] = !empty($Pdata['conservation']) ? str_replace(',','',$Pdata['conservation']) : '';          //回现保守
        $data['radical'] = !empty($Pdata['radical']) ? str_replace(',','',$Pdata['radical']) : '';          //回现激进
        $data['recall'] = !empty($Pdata['recall']) ? $Pdata['recall'] : '';          //回收预评估价值说明
        $params['project_id'] = $data['Id'];
        $stateData = Project::saveProjectEvaluation($params, $data);
        if ($stateData['code'] == 200) {
            $tableModel = "common\models\ProjectPreEvaluationValueEvaluation";
            $projectUnlock = ProjectLock::Unlock($tableModel, $project_id, 'project_id');
            if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                //---编辑资产包-发送消息--fly---
                self::actionPostMessage($project_id);
                //---编辑资产包-发送消息--fly---
                return json_encode(Responses::response200('', 1, '保存成功'));
            } else {
                return json_encode(Responses::response400($projectUnlock['message']));
            }
        }
        return false;
    }


    /*
     * 异步添加/更新 补充说明
     *
     */
    public function actionAjaxSaveOtherNoteProject()
    {
        $Pdata = \Yii::$app->request->post('data');          //项目id
        $data = [];
        $project_id = !empty($Pdata['project_id']) ? $Pdata['project_id'] : 1;
        $data['Id'] = !empty($Pdata['project_id']) ? $Pdata['project_id'] : 1;          //id
        $data['legal'] = !empty($Pdata['legal']) ? $Pdata['legal'] : '';          //法律依据
        $data['sell_plan'] = !empty($Pdata['sell_plan']) ? $Pdata['sell_plan'] : '';          //处置方案
        $data['risk_point'] = !empty($Pdata['risk_point']) ? $Pdata['risk_point'] : '';          //风险点
        $data['current_state'] = !empty($Pdata['current_state']) ? $Pdata['current_state'] : '';          //承债人现状
        $data['other_problem'] = !empty($Pdata['other_problem']) ? $Pdata['other_problem'] : '';          //其他问题
        $data['more_problem'] = !empty($Pdata['more_problem']) ? $Pdata['more_problem'] : '';          //需再补充
        $params['project_id'] = $data['Id'];
        $stateData = Project::saveProjectOtherNote($params, $data);
        if ($stateData['code'] == 200) {
            $tableModel = "common\models\ProjectPreEvaluationOtherNote";
            $projectUnlock = ProjectLock::Unlock($tableModel, $project_id, 'project_id');
            if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                //---编辑资产包-发送消息--fly---
                self::actionPostMessage($project_id);
                //---编辑资产包-发送消息--fly---
                return json_encode(Responses::response200('', 1, '保存成功'));
            } else {
                return json_encode(Responses::response400($projectUnlock['message']));
            }
        }
        return false;
    }

    /*
     * 异步添加/更新 流转
     */
    public function actionAjaxSaveTransgerHistoryProject()
    {
        $Pdata = \Yii::$app->request->post('data');          //id
        $project_id = Yii::$app->request->post('project_id');
        $params['project_id'] = Yii::$app->request->post('project_id');

        $stateData = Project::saveProjectTransferHistory2($params, $Pdata);
        if ($stateData['code'] == 200) {
            $tableModel = "backend\models\ProjectTransferHistory";
            $projectUnlock = ProjectLock::Unlock($tableModel, $project_id, 'project_id');
            if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                //---编辑资产包-发送消息--fly---
                self::actionPostMessage($project_id);
                //---编辑资产包-发送消息--fly---
                return json_encode(Responses::response200('', 1, '保存成功'));
            } else {
                return json_encode(Responses::response400($projectUnlock['message']));
            }
        }
        return false;
    }

    /*
 * 异步添加/更新 团队
 */
    public function actionAjaxSaveTeamProject()
    {

        $dataChief = \Yii::$app->request->post('dataChief');          //id
        $dataLeader = \Yii::$app->request->post('dataLeader');          //id
        $dataUser = \Yii::$app->request->post('dataUser');          //id
        $content = \Yii::$app->request->post('content');          //id
        $project_id = \Yii::$app->request->post('project_id');          //id

        $dataChief = !empty($dataChief) ? $dataChief : '';
        $dataLeader = !empty($dataLeader) ? $dataLeader : '';
        $dataUser = !empty($dataUser) ? $dataUser : '';
        if($dataChief[0]!='请选择')
            $teamMembersData['dataChief'] = PackageInitiationPlan::getUserId($dataChief, 1);
        else
            $teamMembersData['dataChief'] = "0";
        if($dataLeader[0]!='请选择')
            $teamMembersData['dataLeader'] = PackageInitiationPlan::getUserId($dataLeader, 1);
        else
            $teamMembersData['dataLeader'] = "0";
        if($dataUser!='')
            $teamMembersData['dataUser'] = PackageInitiationPlan::getUserId($dataUser, 0);
        else
            $teamMembersData['dataUser'] = "0";
        $data = [
            'manager' => $teamMembersData['dataChief'],
            'owner' => $teamMembersData['dataLeader'],
            'partner' => $teamMembersData['dataUser'],
            'explain' => $content,
            'project_id' => $project_id
        ];
        $params['project_id'] = $project_id;
        $stateData = Project::saveProjectTeam($params, $data);
        if ($stateData['code'] == 200) {
            //如果上传人和资产包负责人不相同--则更改access状态-----start---
            $projectTeamModel = ProjectTeam::findOne(['project_id'=>$project_id]);
            if (!empty($projectTeamModel)){
                $projectModelAccess = Project::findOne($project_id);
                if (!empty($projectModelAccess)){
                    $pacakgeOwner = Package::findOne($projectModelAccess->package_id);
                    if (!empty($pacakgeOwner)&&$teamMembersData['dataLeader']!=$pacakgeOwner->owner){
                        $projectModelAccess->access = 2;
                        $projectModelAccess->save(false);
                    }
                }
            }
            //如果上传人和资产包负责人不相同--则更改access状态-----end---
            //---编辑资产包-发送消息--fly---
            self::actionPostMessage($project_id);
            //---编辑资产包-发送消息--fly---
            $tableModel = "common\models\ProjectTeam";
            $projectUnlock = ProjectLock::Unlock($tableModel, $project_id, 'project_id');
            if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                return json_encode(Responses::response200('', 1, '保存成功'));
            } else {
                return json_encode(Responses::response400($projectUnlock['message']));
            }
        }
        return false;
    }

    /*
     * 异步删除流转
     */
    public function actionAjaxDelTransgerHistoryProject()
    {
        $params['id'] = \Yii::$app->request->post('id');          //id
        $params['project_id'] = Yii::$app->request->post('project_id');
        $stateData = Project::delProjectTransferHistory($params);
        if ($stateData) {
            //---编辑资产包-发送消息--fly---
            self::actionPostMessage($params['project_id']);
            //---编辑资产包-发送消息--fly---
            return true;
        }
        return false;
    }

    /*
     * 异步添加/更新 转让信息
     */
    public function actionAjaxSaveTransferProject()
    {
        $Pdata = \Yii::$app->request->post('data');          //项目id
        //判断是 居间人还是持有人 ， 中间人则添加或更新；持有人则只更新持有人数据删除中间人数，
        // 1为持有人 2居间人
        $data = [];
        $project_id = !empty($Pdata['project_id']) ? $Pdata['project_id'] : 1;
        $data['Id'] = !empty($Pdata['project_id']) ? $Pdata['project_id'] : 1;          //id
        $data['package_id'] = !empty($Pdata['package_id']) ? $Pdata['package_id'] : 1;          //id
        $data['method'] = !empty($Pdata['method']) ? $Pdata['method'] : 1;
        $data['wish'] = !empty($Pdata['wish']) ? $Pdata['wish'] : '';
        $data['expected_transfer'] = !empty($Pdata['expected_transfer']) ? $Pdata['expected_transfer'] : '';
        $data['detail'] = !empty($Pdata['detail']) ? $Pdata['detail'] : '';
        $params['project_id'] = $data['Id'];
        if ($Pdata['state'] == 1) {
            $data['transfer'] = 1;
            $data['state'] = 1;
            $data['contact'] = !empty($Pdata['contact']) ? $Pdata['contact'] : '';
            $data['phone'] = !empty($Pdata['phone']) ? $Pdata['phone'] : '';
            $data['address'] = !empty($Pdata['address']) ? $Pdata['address'] : '';
            $data['position'] = !empty($Pdata['position']) ? $Pdata['position'] : '';
            $data['remark'] = !empty($Pdata['remark']) ? $Pdata['remark'] : '';
            $data['email'] = !empty($Pdata['email']) ? $Pdata['email'] : '';
            $stateData = Project::saveProjectTransfer($params, $data);
            if ($stateData) {
                $tableModel = "common\models\ProjectTransfer";
                $projectUnlock = ProjectLock::Unlock($tableModel, $project_id, 'project_id');
                if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                    //---编辑资产包-发送消息--fly---
                    self::actionPostMessage($project_id);
                    //---编辑资产包-发送消息--fly---

                    return json_encode(Responses::response200('', 1, '保存成功'));
                } else {
                    return json_encode(Responses::response400($projectUnlock['message']));
                }
            }
        } else {
            $dataJu['transfer'] = 2;
            $dataChi['transfer'] = 1;
            $dataJu['state'] = $dataChi['state'] = 2;
            $dataJu['Id'] = !empty($Pdata['project_id']) ? $Pdata['project_id'] : 1;          //id
            $dataJu['package_id'] = !empty($Pdata['package_id']) ? $Pdata['package_id'] : 1;          //id
            $dataJu['method'] = !empty($Pdata['method']) ? $Pdata['method'] : 1;
            $dataJu['wish'] = !empty($Pdata['wish']) ? $Pdata['wish'] : '';
            $dataJu['expected_transfer'] = !empty($Pdata['expected_transfer']) ? $Pdata['expected_transfer'] : '';
            $dataJu['detail'] = !empty($Pdata['detail']) ? $Pdata['detail'] : '';
            $dataJu['contact'] = !empty($Pdata['contactJu']) ? $Pdata['contactJu'] : '';
            $dataJu['phone'] = !empty($Pdata['phoneJu']) ? $Pdata['phoneJu'] : '';
            $dataJu['address'] = !empty($Pdata['addressJu']) ? $Pdata['addressJu'] : '';
            $dataJu['position'] = !empty($Pdata['positionJu']) ? $Pdata['positionJu'] : '';
            $dataJu['remark'] = !empty($Pdata['remarkJu']) ? $Pdata['remarkJu'] : '';
            $dataJu['email'] = !empty($Pdata['emailJu']) ? $Pdata['emailJu'] : '';
            $dataChi['Id'] = !empty($Pdata['project_id']) ? $Pdata['project_id'] : 1;          //id
            $dataChi['package_id'] = !empty($Pdata['package_id']) ? $Pdata['package_id'] : 1;          //id
            $dataChi['method'] = !empty($Pdata['method']) ? $Pdata['method'] : 1;
            $dataChi['wish'] = !empty($Pdata['wish']) ? $Pdata['wish'] : '';
            $dataChi['expected_transfer'] = !empty($Pdata['expected_transfer']) ? $Pdata['expected_transfer'] : '';
            $dataChi['detail'] = !empty($Pdata['detail']) ? $Pdata['detail'] : '';
            $dataChi['contact'] = !empty($Pdata['contactChi']) ? $Pdata['contactChi'] : '';
            $dataChi['phone'] = !empty($Pdata['phoneChi']) ? $Pdata['phoneChi'] : '';
            $dataChi['address'] = !empty($Pdata['addressChi']) ? $Pdata['addressChi'] : '';
            $dataChi['email'] = !empty($Pdata['emailChi']) ? $Pdata['emailChi'] : '';
            $dataChi['position'] = !empty($Pdata['positionChi']) ? $Pdata['positionChi'] : '';
            $dataChi['remark'] = !empty($Pdata['remarkChi']) ? $Pdata['remarkChi'] : '';
            $stateDataJu = Project::saveProjectTransfer($params, $dataJu);
            $stateDataDhi = Project::saveProjectTransfer($params, $dataChi);
            if ($stateDataJu && $stateDataDhi) {
                $tableModel = "common\models\ProjectTransfer";
                $projectUnlock = ProjectLock::Unlock($tableModel, $project_id, 'project_id');
                if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                    //---编辑资产包-发送消息--fly---
                    self::actionPostMessage($project_id);
                    //---编辑资产包-发送消息--fly---

                    return json_encode(Responses::response200('', 1, '保存成功'));
                } else {
                    return json_encode(Responses::response400($projectUnlock['message']));
                }
            }
        }

        return false;
    }

    /*
     * 查看单项目信息混合类信息
     */
    public function actionGetinfodata()
    {
        //-------------修改消息状态--变为已读----fly---------------------
        $messageState = Yii::$app->request->get('message_state', 1);
        $follow = Yii::$app->request->get('follow', 0);
        if ($messageState == 2) {
            $param['message_user_group_id'] = Yii::$app->request->get('message_user_group_id', 1);
            $user_id = \Yii::$app->user->getId();
            $state = 0;
            $instationMessageState = InstationMessage::readAdminMessage($param);
            if (!empty($follow)) {
                $param['user_id'] = Yii::$app->request->get('user_id', 1);
                $instationMessageState = InstationMessage::readLikeMessage($param);
            }
            if ($instationMessageState['code'] == 400) {
                return false;
            }
        }
        //-------------修改消息状态--变为已读----fly---------------------
        $data['Id'] = intval(\Yii::$app->request->get('project_id', 1));          //
        $data['package_id'] = intval(\Yii::$app->request->get('package_id', 1));          //
        $data['mortgage_id'] = intval(\Yii::$app->request->get('mortgage_id', 1));          //
        $project_id = $data['Id'];
		$result = \backend\controllers\DtActionFilter::checkProject('project_view',$project_id);
		if(!$result){echo '<meta charset="UTF-8">没有权限访问 ';exit;}
        $data = Project::getProjectInfoData($data);

        $data['data']['res']['provinceData'] = SearchPackage::getProvinces('pid=0');
        //所有部门人员
        $userModel = new UserModel();
//        $where = ['not in', 'department',
//            ['总裁办', '风控管理中心', '财务部', '技术部', '品牌部', '新大唐学院', '人力行政部',
//                'ceooffice', 'windControlManagementCenter', 'finance', 'technology', 'brand', 'college', 'humanAdministration','',
//            ]];
        $where = ['in','department',['project1','project2','project3','project6','foreignAffairsOffice']];
        $data['data']['res']['Base']['departments'] = $userModel->getDepartmentUsers($where);
        $data['data']['res']['Base']['access_users_ids'] = $data['data']['res']['Base']['access_users'] != "" ? explode(",", $data['data']['res']['Base']['access_users']) : "";
        $data['data']['res']['Base']['access_users'] = $this->getAccessUsers($data['data']['res']['Base']['access'], $data['data']['res']['Base']['access']);
        //是否关注
        $data_like = ProjectLike::find()->where(['project_id' => $data['data']['res']['Base']['id'], 'type' => 1, 'user_id' => Yii::$app->user->id])->asArray()->one();
        if ($data_like['id']) {
            $data['data']['res']['Base']['flow'] = 1;
        } else {
            $data['data']['res']['Base']['flow'] = 0;
        }
        //是否亮点
        $data_like = ProjectLike::find()->where(['project_id' => $data['data']['res']['Base']['id'], 'type' => 2,])->asArray()->one();
        if ($data_like['id']) {
            $data['data']['res']['Base']['light_spot'] = 1;
        } else {
            $data['data']['res']['Base']['light_spot'] = 0;
        }
        //获取配置团队成员信息
        $teamZJ = array_column($data['data']['res']['teamZJ'], 'id');
        $teamFZR = array_column($data['data']['res']['teamFZR'], 'id');
        $teamXZR = array_column($data['data']['res']['teamXZR'], 'id');

//        $teamS = array_merge($teamZJ, $teamFZR, $teamXZR);
//        $data['data']['res']['teamInfo'] = Project::getTeamUserData($teamS);

        $data['data']['res']['teamInfo']['teamZJ'] = array();
        $data['data']['res']['teamInfo']['teamFZR'] = array();
        $data['data']['res']['teamInfo']['teamXZR'] = array();
        $getDepartmentUsersList = (new UserModel())->getDepartmentUsersList();

        if (!empty($teamZJ)) {
            foreach ($teamZJ as $value) {
                if (isset($getDepartmentUsersList[$value])) {
                    $teamZJ_array['id'] = $getDepartmentUsersList[$value]['id'];
                    $teamZJ_array['realname'] = $getDepartmentUsersList[$value]['realname'];
                    $teamZJ_array['username'] = $getDepartmentUsersList[$value]['username'];
                    $teamZJ_array['department'] = $getDepartmentUsersList[$value]['description'];
                    $teamZJ_array['avatar'] = $getDepartmentUsersList[$value]['avatar'];
                    $teamZJ_array['role'] = '项目总监';
                    $data['data']['res']['teamInfo']['teamZJ'][] = $teamZJ_array;
                }
            }
        }

        if (!empty($teamFZR)) {
            foreach ($teamFZR as $value) {
                if (isset($getDepartmentUsersList[$value])) {
                    $teamFZR_array['id'] = $getDepartmentUsersList[$value]['id'];
                    $teamFZR_array['realname'] = $getDepartmentUsersList[$value]['realname'];
                    $teamFZR_array['username'] = $getDepartmentUsersList[$value]['username'];
                    $teamFZR_array['department'] = $getDepartmentUsersList[$value]['description'];
                    $teamFZR_array['avatar'] = $getDepartmentUsersList[$value]['avatar'];
                    $teamFZR_array['role'] = '项目经理';
                    $data['data']['res']['teamInfo']['teamFZR'][] = $teamFZR_array;
                }
            }
        }

        if (!empty($teamXZR)) {
            foreach ($teamXZR as $value) {
                if (isset($getDepartmentUsersList[$value])) {
                    $teamXZR_array['id'] = $getDepartmentUsersList[$value]['id'];
                    $teamXZR_array['realname'] = $getDepartmentUsersList[$value]['realname'];
                    $teamXZR_array['username'] = $getDepartmentUsersList[$value]['username'];
                    $teamXZR_array['department'] = $getDepartmentUsersList[$value]['description'];
                    $teamXZR_array['avatar'] = $getDepartmentUsersList[$value]['avatar'];
                    $teamXZR_array['role'] = '团队成员';
                    $data['data']['res']['teamInfo']['teamXZR'][] = $teamXZR_array;
                }
            }
        }

        //项目所属资产包
        $ofPackageId = \Yii::$app->request->get('package_id', 1);
        $packageInfo = Package::findOne($ofPackageId);
        if (!empty($packageInfo)) {
            $data['data']['res']['packageName'] = $packageInfo->title;
            $data['data']['res']['state'] = $packageInfo->state;
            // $data['data']['res']['Base']['code'] = $packageInfo->code;
            $province = '';
            $city = '';
            $country = new \common\models\Country();
            if ($packageInfo->province > 0) {
                $province = $country->getName($packageInfo->province);
            }
            if ($packageInfo->city > 0) {
                $city = $country->getName($packageInfo->city);
            }
            $data['data']['res']['Base']['country'] = $province . $city;
        } else {
            $data['data']['res']['packageName'] = '';
            //$data['data']['res']['Base']['code'] = '';
            $data['data']['res']['Base']['country'] = '';
        }
        //$data['data']['res']['packageName'] = (new \yii\db\Query())->from(Package::tableName())->where(['=', 'id', $ofPackageId])->one()['title'];

        //项目详情
        $project = Project::findOne((int)$project_id);
        $data['data']['res']['project'] = $project;

        if (!empty($data) && $data['code'] == 200) {
            if ($data['data']['res']['Base']['type'] == 2) {
                return $this->render('project-mortgage', $data['data']['res']);
            } else {
                return $this->render('project-details', $data['data']['res']);
            }
        }
        return false;
    }

    /*获取公开部门显示结果*/
    private function getAccessUsers($access, $accessStr)
    {
        switch ($access) {
            case 2:
                $access_users = (new UserModel())->getUserStr($accessStr);//可访问的用户str
                break;
            case 1:
                $access_users = '私密';
                break;
            default:
                $access_users = '公司全体人员';
                break;
        }
        return $access_users;
    }

    /*
 * 查看单项目信息混合类信息
 */
    public function actionGetBaseData()
    {
        //查看锁状态
        $project_id = intval(\Yii::$app->request->get('project_id', 0));          //
        $ppesid = intval(\Yii::$app->request->get('ppesid', 0));          //
        $data['Id'] = $project_id;          //
        $data['package_id'] = intval(\Yii::$app->request->get('package_id', 1));          //
        $data = Project::getProjectInfoData($data);
        $data['data']['res']['provinceData'] = SearchPackage::getProvinces('pid=0');
        $userId = Yii::$app->user->getId();
        if (!empty($data) && $data['code'] == 200) {
            $postion = intval(\Yii::$app->request->get('postion', 1));          //显示位置1
            switch ($postion) {
                case 1:
                    $tableModel = "common\models\Project";
                    $projectBase = ProjectLock::SelectLock($tableModel, $project_id, 'id');
                    if (!empty($projectBase) && $projectBase['code'] == 200) {
                        //加锁
                        $projectLock = ProjectLock::Lock($tableModel, $userId, $project_id, 'id');
                        if (!empty($projectLock) && $projectLock['code']) {
                            return json_encode(Responses::response200($this->renderPartial('base-edit', $data['data']['res'])));
                        } else {
                            return json_encode(Responses::response400($projectLock['message']));
                        }
                    } else {
                        return json_encode(Responses::response400($projectBase['message']));
                    }
                    break;
                case 2:
                    return $this->renderPartial('base', $data['data']['res']);
                    break;
                case 3:
                    $tableModel = "common\models\ProjectPreEvaluationLawsuit";
                    $projectBase = ProjectLock::SelectLock($tableModel, $project_id, 'project_id');
                    if (!empty($projectBase) && $projectBase['code'] == 200) {
                        //加锁
                        $projectLock = ProjectLock::Lock($tableModel, $userId, $project_id, 'project_id');
                        if (!empty($projectLock) && $projectLock['code']) {
                            return json_encode(Responses::response200($this->renderPartial('judicial-edit', $data['data']['res'])));
                        } else {
                            return json_encode(Responses::response400($projectLock['message']));
                        }
                    } else {
                        return json_encode(Responses::response400($projectBase['message']));
                    }
                    break;
                case 4:
                    return $this->renderPartial('judicial', $data['data']['res']);
                    break;
                case 5:
                    $tableModel = "common\models\ProjectPreEvaluationValueEvaluation";
                    $projectBase = ProjectLock::SelectLock($tableModel, $project_id, 'project_id');
                    if (!empty($projectBase) && $projectBase['code'] == 200) {
                        //加锁
                        $projectLock = ProjectLock::Lock($tableModel, $userId, $project_id, 'project_id');
                        if (!empty($projectLock) && $projectLock['code']) {
                            return json_encode(Responses::response200($this->renderPartial('assessment-edit', $data['data']['res'])));
                        } else {
                            return json_encode(Responses::response400($projectLock['message']));
                        }
                    } else {
                        return json_encode(Responses::response400($projectBase['message']));
                    }
                    break;
                case 6:
                    return $this->renderPartial('assessment', $data['data']['res']);
                    break;
                case 7:
                    $tableModel = "common\models\ProjectPreEvaluationOtherNote";
                    $projectBase = ProjectLock::SelectLock($tableModel, $project_id, 'project_id');
                    if (!empty($projectBase) && $projectBase['code'] == 200) {
                        //加锁
                        $projectLock = ProjectLock::Lock($tableModel, $userId, $project_id, 'project_id');
                        if (!empty($projectLock) && $projectLock['code']) {
                            return json_encode(Responses::response200($this->renderPartial('explain-edit', $data['data']['res'])));
                        } else {
                            return json_encode(Responses::response400($projectLock['message']));
                        }
                    } else {
                        return json_encode(Responses::response400($projectBase['message']));
                    }
                    break;
                case 8:
                    return $this->renderPartial('explain', $data['data']['res']);
                    break;
                case 9:
                    $tableModel = "common\models\ProjectTransfer";
                    $projectBase = ProjectLock::SelectLock($tableModel, $project_id, 'project_id');
                    if (!empty($projectBase) && $projectBase['code'] == 200) {
                        //加锁
                        $projectLock = ProjectLock::Lock($tableModel, $userId, $project_id, 'project_id');
                        if (!empty($projectLock) && $projectLock['code']) {
                            return json_encode(Responses::response200($this->renderPartial('make-edit', $data['data']['res'])));
                        } else {
                            return json_encode(Responses::response400($projectLock['message']));
                        }
                    } else {
                        return json_encode(Responses::response400($projectBase['message']));
                    }
                    break;
                case 10:
                    return $this->renderPartial('make', $data['data']['res']);
                    break;
                case 11:
                    $tableModel = "backend\models\ProjectTransferHistory";
                    $projectBase = ProjectLock::SelectLock($tableModel, $project_id, 'project_id');
                    if (!empty($projectBase) && $projectBase['code'] == 200) {
                        //加锁
                        $projectLock = ProjectLock::Lock($tableModel, $userId, $project_id, 'project_id');
                        if (!empty($projectLock) && $projectLock['code']) {
                            return json_encode(Responses::response200($this->renderPartial('maintain-edit', $data['data']['res'])));
                        } else {
                            return json_encode(Responses::response400($projectLock['message']));
                        }
                    } else {
                        return json_encode(Responses::response400($projectBase['message']));
                    }
                    break;
                case 12:
                    return $this->renderPartial('maintain', $data['data']['res']);
                    break;
                case 13:
                    $tableModel = "common\models\ProjectTeam";
                    $projectBase = ProjectLock::SelectLock($tableModel, $project_id, 'project_id');
                    if (!empty($projectBase) && $projectBase['code'] == 200) {
                        //加锁
                        $projectLock = ProjectLock::Lock($tableModel, $userId, $project_id, 'project_id');
                        if (!empty($projectLock) && $projectLock['code']) {
                            return json_encode(Responses::response200($this->renderPartial('team-edit', $data['data']['res'])));
                        } else {
                            return json_encode(Responses::response400($projectLock['message']));
                        }
                    } else {
                        return json_encode(Responses::response400($projectBase['message']));
                    }
                    break;
                case 14:
                    return $this->renderPartial('team', $data['data']['res']);
                    break;

                //----抵押类加锁---
                case 15:
                    //抵押物列表
                    $tableModel = "common\models\ProjectPreEvaluationMortgage";
                    if (!empty($data['data']['res']['mortgageStateList'])) {
                        $projectBase = ProjectLock::SelectLock($tableModel, $project_id, 'project_id');
                        if (!empty($projectBase) && $projectBase['code'] == 200) {
                            //加锁
                            $projectLock = ProjectLock::Lock($tableModel, $userId, $project_id, 'project_id');
                            if (!empty($projectLock) && $projectLock['code']) {
                                return json_encode(Responses::response200($this->renderPartial('assessment-edit', $data['data']['res'])));
                            } else {
                                return json_encode(Responses::response400($projectLock['message']));
                            }
                        } else {
                            return json_encode(Responses::response400($projectBase['message']));
                        }
                    }
                    return json_encode(Responses::response200($this->renderPartial('assessment-edit', $data['data']['res'])));
                    break;
                case 111:
                    //抵押物列表--抵押物信息
                    $tableModel = "backend\models\ProjectPreEvaluationSeal";
                    $projectBase = ProjectLock::SelectLock($tableModel, $ppesid, 'id');
                    if (!empty($projectBase) && $projectBase['code'] == 200) {
                        //加锁
                        $projectLock = ProjectLock::Lock($tableModel, $userId, $ppesid, 'id');
                        if (!empty($projectLock) && $projectLock['code']) {
                            return json_encode(Responses::response200($this->renderPartial('assessment-edit', $data['data']['res'])));
                        } else {
                            return json_encode(Responses::response400($projectLock['message']));
                        }
                    } else {
                        return json_encode(Responses::response400($projectBase['message']));
                    }
                    break;
                case 114:
                    //抵押物列表--现场访谈
                    $tableModel = "backend\models\ProjectPreEvaluationInterview";
                    $projectBase = ProjectLock::SelectLock($tableModel, $ppesid, 'id');
                    if (!empty($projectBase) && $projectBase['code'] == 200) {
                        //加锁
                        $projectLock = ProjectLock::Lock($tableModel, $userId, $ppesid, 'id');
                        if (!empty($projectLock) && $projectLock['code']) {
                            return json_encode(Responses::response200($this->renderPartial('assessment-edit', $data['data']['res'])));
                        } else {
                            return json_encode(Responses::response400($projectLock['message']));
                        }
                    } else {
                        return json_encode(Responses::response400($projectBase['message']));
                    }
                    break;
                case 115:
                    //抵押物列表--现场访谈
                    $tableModel = "backend\models\ProjectPreEvaluationValue";
                    $projectBase = ProjectLock::SelectLock($tableModel, $ppesid, 'ppes');
                    if (!empty($projectBase) && $projectBase['code'] == 200) {
                        //加锁
                        $projectLock = ProjectLock::Lock($tableModel, $userId, $ppesid, 'ppes');
                        if (!empty($projectLock) && $projectLock['code']) {
                            return json_encode(Responses::response200($this->renderPartial('assessment-edit', $data['data']['res'])));
                        } else {
                            return json_encode(Responses::response400($projectLock['message']));
                        }
                    } else {
                        return json_encode(Responses::response400($projectBase['message']));
                    }
                    break;
                case 21:
                    //抵押物--非抵押物情况
                    $tableModel = "backend\models\ProjectPreEvaluationOtherValue";
                    $projectBase = ProjectLock::SelectLock($tableModel, $project_id, 'project_id');
                    if (!empty($projectBase) && $projectBase['code'] == 200) {
                        //加锁
                        $projectLock = ProjectLock::Lock($tableModel, $userId, $project_id, 'project_id');
                        if (!empty($projectLock) && $projectLock['code']) {
                            return json_encode(Responses::response200($this->renderPartial('assessment-edit', $data['data']['res'])));
                        } else {
                            return json_encode(Responses::response400($projectLock['message']));
                        }
                    } else {
                        return json_encode(Responses::response400($projectBase['message']));
                    }
                    break;
                case 22:
                    //抵押物--回现评估
                    $tableModel = "common\models\ProjectPaymentCollection";
                    $projectBase = ProjectLock::SelectLock($tableModel, $project_id, 'project_id');
                    if (!empty($projectBase) && $projectBase['code'] == 200) {
                        //加锁
                        $projectLock = ProjectLock::Lock($tableModel, $userId, $project_id, 'project_id');
                        if (!empty($projectLock) && $projectLock['code']) {
                            return json_encode(Responses::response200($this->renderPartial('assessment-edit', $data['data']['res'])));
                        } else {
                            return json_encode(Responses::response400($projectLock['message']));
                        }
                    } else {
                        return json_encode(Responses::response400($projectBase['message']));
                    }
                    break;
                //----抵押类加锁---
                default:
                    $tableModel = "common\models\Project";
                    $projectBase = ProjectLock::SelectLock($tableModel, $project_id, 'id');
                    if (!empty($projectBase) && $projectBase['code'] == 200) {
                        //加锁
                        $projectLock = ProjectLock::Lock($tableModel, $userId, $project_id, 'id');
                        if (!empty($projectLock) && $projectLock['code']) {
                            return json_encode(Responses::response200($this->renderPartial('base-edit', $data['data']['res'])));
                        } else {
                            return json_encode(Responses::response400($projectLock['message']));
                        }
                    } else {
                        return json_encode(Responses::response400($projectBase['message']));
                    }
                    break;
            }
        }
        return false;
    }


    /**
     * 项目权限更新
     * @auth yangtao
     * @return \yii\web\Response
     */
    public function actionSetPermissions()
    {

        $this->layout = 'main2';
        $project_id = Yii::$app->request->get('projectid');
        $userModel = new UserModel();
        if ($post = Yii::$app->request->post()) {
            $id = $post['projectid'];
            $no_ajax = $post['no_ajax'];
            //访问类型
            $access = (int)$post['Package']['access'];
            switch ($access) {
                case 0:
                    $userList = $userModel->getList(array());
                    $access_users = ArrayHelper::getColumn($userList, 'id');
                    break;
                case 1:
                    $data = ['or',
                        ['in', 'department', ['总裁办', '风控管理中心', '财务部', '技术部']],
                        ['in', 'department', ['ceooffice', 'windControlManagementCenter', 'finance', 'technology']]
                    ];
                    $userList = $userModel->getList($data);
                    $access_users = ArrayHelper::getColumn($userList, 'id');
                    break;
                case 2:
                    //总裁办、风控管理中心、财务部、技术部等部门人员
                    $data = ['or',
                        ['in', 'department', ['总裁办', '风控管理中心', '财务部', '技术部']],
                        ['in', 'department', ['ceooffice', 'windControlManagementCenter', 'finance', 'technology']]
                    ];
                    $userList = $userModel->getList($data);
                    $users = ArrayHelper::getColumn($userList, 'id');
                    //访问人员
                    if (!empty($post['Package']['access_users']) && is_array($post['Package']['access_users'])) {
                        foreach ($post['Package']['access_users'] as $k => $v) {
                            if ($v == '0') {
                                unset($post['Package']['access_users'][$k]);
                            }
                        }
                        $access_users = array_unique(array_merge($post['Package']['access_users'], $users));
                    } else {
                        $access_users = $users;
                    }
                    break;
                default:
            }

            $model = new Project();
            if ($re = $model->setPermissionForProject($access_users, $access, $id)) {
                if (Yii::$app->request->isAjax && !$no_ajax) {
                    if ($re['state']) {
                        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                        return ['status' => true, 'msg' => $re['msg']];
                    } else {
                        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                        return ['status' => false, 'msg' => $re['msg']];
                    }

                } else {
                    if ($re['state']) {
                        Yii::$app->getSession()->setFlash('success', $re['msg']);
                    } else {
                        Yii::$app->getSession()->setFlash('error', $re['msg']);
                    }
                    return $this->render("modal/asset-project-editing-permissions");

                }
            }
        }



        $data = Project::find()->where('id=:id', [':id' => $project_id])->asArray()->one();
        if (empty($data)) {
            throw new \Exception('error');
        }

        $result = \backend\controllers\DtActionFilter::checkProject('project_permissions',$project_id);
        if(!$result){
            if (Yii::$app->request->isAjax) {
                $response = Yii::$app->response;
                $response->format = \yii\web\Response::FORMAT_JSON;
                $response->data = ['status' => 'false','msg'=>Yii::t('yii', 'You are not allowed to perform this action.')];
                $response->send();
                exit;
            }else{
                throw new  \yii\web\ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
            }
        }

        if (Yii::$app->request->isAjax) {
            $no_ajax = 0;
        } else {
            $no_ajax = 1;
        }
        //所有部门人员
        $userModel = new UserModel();
//        $where = ['not in', 'department',
//            ['总裁办', '风控管理中心', '财务部', '技术部', '', '品牌部', '新大唐学院', '人力行政部',
//                'ceooffice', 'windControlManagementCenter', 'finance', 'technology', 'brand', 'college', 'humanAdministration','',
//            ]];
        $where = ['in','department',['project1','project2','project3','project6','foreignAffairsOffice']];
        $data['departments'] = $userModel->getDepartmentUsers($where);
        $data['access_users_ids'] = explode(",", $data['access_users']);
        $data['access_users'] = $this->getAccessUsers($data['access'], $data['access']);
        return $this->render("modal/asset-project-editing-permissions", ['no_ajax' => $no_ajax, 'projectid' => $data['id'], 'departments' => $data['departments'], 'access' => $data['access'], 'access_users_ids' => $data['access_users_ids']]);
    }

    /**
     * 项目的关注
     * @return array
     * @throws \Exception
     */
    public function actionSetProjectLike()
    {
        //1关注 2 亮点
        $userId = Yii::$app->user->id;
        if (!$userId) {
            throw new \Exception('请先登录。');
        }
        $project_id = Yii::$app->request->get('project_id');
        $del = Yii::$app->request->get('del');
        $type = Yii::$app->request->get('type');
        if (empty($type)) {
            $type = 1;
        }
        if ($del) {
            $data = Project::find()->where(['id' => $project_id])->asArray()->one();
            if (empty($data)) {
                throw new \Exception('没有对应的项目。');
            }
            $model = ProjectLike::findOne(['project_id' => $project_id, 'user_id' => $userId, 'type' => $type]);
            $result = $model->delete();
            if ($result && empty($model->getErrors())) {
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                if ($type == 1) {
                    $projectLog = new ProjectLog();
                    $projectLog->project_id = $project_id;
                    $projectLog->created_at = date('Y-m-d H:i:s');
                    $projectLog->user_id = $userId;
                    $projectLog->log = "取消关注成功";
                    $re = $projectLog->save();
                    if (!$re) {
                        throw new Exception('单项目日志保存失败');
                    }
                    return ['status' => true, 'msg' => '取消关注成功', 'img' => '/image/projectDetails/focus.png', 'type' => 0];
                } else {
                    $projectLog = new ProjectLog();
                    $projectLog->project_id = $project_id;
                    $projectLog->created_at = date('Y-m-d H:i:s');
                    $projectLog->user_id = $userId;
                    $projectLog->log = "取消标记亮点成功";
                    $re = $projectLog->save();
                    if (!$re) {
                        throw new Exception('单项目日志保存失败');
                    }
                    return ['status' => true, 'msg' => '取消标记亮点成功', 'img' => '/image/projectDetails/liangDian.png', 'type' => 0];
                }

            } else {
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                if ($type == 1) {
                    return ['status' => false, 'msg' => '取消关注失败', 'img' => '/image/projectDetails/focus.png', 'type' => $type];
                } else {
                    return ['status' => false, 'msg' => '取消标记亮点失败', 'img' => '/image/projectDetails/liangDian.png', 'type' => $type];
                }
            }

        } else {
            $model = new ProjectLike();
            $model->type = $type;
            $model->project_id = $project_id;
            $model->user_id = $userId;

            $result = $model->save();
            if ($result && empty($model->getErrors())) {
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                if ($type == 1) {
                    $projectLog = new ProjectLog();
                    $projectLog->project_id = $project_id;
                    $projectLog->created_at = date('Y-m-d H:i:s');
                    $projectLog->user_id = $userId;
                    $projectLog->log = "关注成功";
                    $re = $projectLog->save();
                    if (!$re) {
                        throw new Exception('单项目日志保存失败');
                    }
                    return ['status' => true, 'msg' => '关注成功', 'img' => '/image/projectDetails/isfocus.png', 'type' => 1];
                } else {
                    $projectLog = new ProjectLog();
                    $projectLog->project_id = $project_id;
                    $projectLog->created_at = date('Y-m-d H:i:s');
                    $projectLog->user_id = $userId;
                    $projectLog->log = "标记亮点成功";
                    $re = $projectLog->save();
                    if (!$re) {
                        throw new Exception('单项目日志保存失败');
                    }
                    return ['status' => true, 'msg' => '标记亮点成功', 'img' => '/image/projectDetails/isliangDian.png', 'type' => 1];
                }
            } else {
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                if ($type == 1) {
                    return ['status' => false, 'msg' => '关注失败', 'img' => '/image/projectDetails/focus.png', 'type' => $type];
                } else {
                    return ['status' => false, 'msg' => '标记亮点失败', 'img' => '/image/projectDetails/liangDian.png', 'type' => $type];
                }
            }

        }

    }


    /**
     * 项目的标记亮点
     * @return array
     * @throws \Exception
     */
    public function actionSetProjectLight()
    {
        //1关注 2 亮点
        $userId = Yii::$app->user->id;
        if (!$userId) {
            throw new \Exception('请先登录。');
        }
        $project_id = Yii::$app->request->get('project_id');
        $del = Yii::$app->request->get('del');
        $type = Yii::$app->request->get('type');
        if (empty($type)) {
            $type = 1;
        }
        if ($del) {
            $data = Project::find()->where(['id' => $project_id])->asArray()->one();
            if (empty($data)) {
                throw new \Exception('没有对应的资产包。');
            }
            $model = ProjectLike::findOne(['project_id' => $project_id, 'user_id' => $userId, 'type' => $type]);
            $result = $model->delete();
            if ($result && empty($model->getErrors())) {
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                if ($type == 1) {
                    $projectLog = new Projectlog();
                    $projectLog->project_id = $project_id;
                    $projectLog->created_at = date('Y-m-d H:i:s');
                    $projectLog->user_id = $userId;
                    $projectLog->log = "取消注关成功";
                    $re = $projectLog->save();
                    if (!$re) {
                        throw new Exception('单项目日志保存失败');
                    }
                    return ['status' => true, 'msg' => '取消注关成功', 'img' => '/image/projectDetails/focus.png', 'type' => 0];
                } else {
                    $projectLog = new Projectlog();
                    $projectLog->project_id = $project_id;
                    $projectLog->created_at = date('Y-m-d H:i:s');
                    $projectLog->user_id = $userId;
                    $projectLog->log = "取消标记亮点成功";
                    $re = $projectLog->save();
                    if (!$re) {
                        throw new Exception('单项目日志保存失败');
                    }
                    Project::updateAll(['is_highlights' => 2], 'id = ' . $project_id);
                    return ['status' => true, 'msg' => '取消标记亮点成功', 'img' => '/image/projectDetails/liangDian.png', 'type' => 0];
                }

            } else {
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                if ($type == 1) {
                    return ['status' => false, 'msg' => '取消关注失败', 'img' => '/image/projectDetails/focus.png', 'type' => $type];
                } else {
                    return ['status' => false, 'msg' => '取消标记亮点失败', 'img' => '/image/projectDetails/liangDian.png', 'type' => $type];
                }
            }

        } else {
            $model = new ProjectLike();
            $model->type = $type;
            $model->project_id = $project_id;
            $model->user_id = $userId;

            $result = $model->save();
            if ($result && empty($model->getErrors())) {
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                if ($type == 1) {
                    $projectLog = new Projectlog();
                    $projectLog->project_id = $project_id;
                    $projectLog->created_at = date('Y-m-d H:i:s');
                    $projectLog->user_id = $userId;
                    $projectLog->log = "关注成功";
                    $re = $projectLog->save();
                    if (!$re) {
                        throw new Exception('单项目日志保存失败');
                    }
                    return ['status' => true, 'msg' => '关注成功', 'img' => '/image/projectDetails/isfocus.png', 'type' => 1];
                } else {
                    $projectLog = new Projectlog();
                    $projectLog->project_id = $project_id;
                    $projectLog->created_at = date('Y-m-d H:i:s');
                    $projectLog->user_id = $userId;
                    $projectLog->log = "标记亮点成功";
                    $re = $projectLog->save();
                    if (!$re) {
                        throw new Exception('单项目日志保存失败');
                    }
                    Project::updateAll(['is_highlights' => 1], 'id = ' . $project_id);
                    return ['status' => true, 'msg' => '标记亮点成功', 'img' => '/image/projectDetails/isliangDian.png', 'type' => 1];
                }
            } else {
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                if ($type == 1) {
                    return ['status' => false, 'msg' => '关注失败', 'img' => '/image/projectDetails/focus.png', 'type' => $type];
                } else {
                    return ['status' => false, 'msg' => '标记亮点失败', 'img' => '/image/projectDetails/liangDian.png', 'type' => $type];
                }
            }
        }
    }


    /**
     * 项目配置团队
     * @auth yangtao
     * @return \yii\web\Response
     */
    public function actionSetTeams()
    {

        $this->layout = 'main2';
        $project_id = Yii::$app->request->get('projectid');
        $userModel = new UserModel();
        if ($post = Yii::$app->request->post()) {
            $id = $post['projectid'];
            $no_ajax = $post['no_ajax'];
            //访问类型
            $access = (int)$post['Package']['access'];
            switch ($access) {
                case 0:
                    $userList = $userModel->getList(array());
                    $access_users = ArrayHelper::getColumn($userList, 'id');
                    break;
                case 1:
                    $data = ['or',
                        ['in', 'department', ['总裁办', '风控管理中心', '财务部', '技术部']],
                        ['in', 'department', ['ceooffice', 'windControlManagementCenter', 'finance', 'technology']]
                    ];
                    $userList = $userModel->getList($data);
                    $access_users = ArrayHelper::getColumn($userList, 'id');
                    break;
                case 2:
                    //总裁办、风控管理中心、财务部、技术部等部门人员
                    $data = ['or',
                        ['in', 'department', ['总裁办', '风控管理中心', '财务部', '技术部']],
                        ['in', 'department', ['ceooffice', 'windControlManagementCenter', 'finance', 'technology']]
                    ];
                    $userList = $userModel->getList($data);
                    $users = ArrayHelper::getColumn($userList, 'id');
                    //访问人员
                    if (!empty($post['Package']['access_users']) && is_array($post['Package']['access_users'])) {
                        foreach ($post['Package']['access_users'] as $k => $v) {
                            if ($v == '0') {
                                unset($post['Package']['access_users'][$k]);
                            }
                        }
                        $access_users = array_unique(array_merge($post['Package']['access_users'], $users));
                    } else {
                        $access_users = $users;
                    }
                    break;
                default:
            }

            $model = new Project();
            if ($re = $model->setPermissionForProject($access_users, $access, $id)) {
                if (Yii::$app->request->isAjax && !$no_ajax) {
                    if ($re['state']) {
                        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                        return ['status' => true, 'msg' => $re['msg']];
                    } else {
                        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                        return ['status' => false, 'msg' => $re['msg']];
                    }

                } else {
                    if ($re['state']) {
                        Yii::$app->getSession()->setFlash('success', $re['msg']);
                    } else {
                        Yii::$app->getSession()->setFlash('error', $re['msg']);
                    }
                    return $this->render("modal/asset-project-editing-permissions");

                }
            }
        }


        $data = Project::find()->where('id=:id', [':id' => $project_id])->asArray()->one();
        if (empty($data)) {
            throw new \Exception('error');
        }

        if (Yii::$app->request->isAjax) {
            $no_ajax = 0;
        } else {
            $no_ajax = 1;
        }
        //所有部门人员
        $userModel = new UserModel();
//        $where = ['not in', 'department',
//            ['总裁办', '风控管理中心', '财务部', '技术部', '', '品牌部', '新大唐学院', '人力行政部',
//                'ceooffice', 'windControlManagementCenter', 'finance', 'technology', 'brand', 'college', 'humanAdministration','',
//            ]];
        $where = ['in','department',['project1','project2','project3','project6','foreignAffairsOffice']];

        $data['departments'] = $userModel->getDepartmentUsers($where);
        $data['access_users_ids'] = explode(",", $data['access_users']);
        $data['access_users'] = $this->getAccessUsers($data['access'], $data['access']);

        $data['user'] = (new \yii\db\Query())->select('*')->from('user')->all();
        $data['userChief'] = (new \yii\db\Query())->select('*')->from('user')->andWhere(['=', 'is_leader', 1])->all();

        $data['team'] = (new \yii\db\Query())->from(ProjectTeam::tableName())->select('*')->where(['=', 'project_id', $data['id']])->one();
        if (!empty($projectInfoData['team'])) {
            //通过id获取总监名称
            $leaderIdArr = [];
            if (!empty($projectInfoData['team']['manager']) && preg_match('/,/', $projectInfoData['team']['manager'])) {
                $leaderIdArr = array_unique(explode(',', $projectInfoData['team']['manager']));
            } else if (is_string($projectInfoData['team']['manager'])) {
                $leaderIdArr = $projectInfoData['team']['manager'];
            }
            $leader_name = (new \yii\db\Query())->select('id,realname,department')->from(UserModel::tableName())->where(['in', 'id', $leaderIdArr])->all();
            $data['teamZJ'] = PackageInitiationPlan::pieceUsername($leader_name);
            //通过id获取负责人名称
            $ownerIdArr = [];
            if (!empty($projectInfoData['team']['owner']) && preg_match('/,/', $projectInfoData['team']['owner'])) {
                $ownerIdArr = array_unique(explode(',', $projectInfoData['team']['owner']));
            } else if (is_string($projectInfoData['team']['owner'])) {
                $ownerIdArr = $projectInfoData['team']['owner'];
            }
            $owner_name = (new \yii\db\Query())->select('id,realname,department')->from(UserModel::tableName())->where(['in', 'id', $ownerIdArr])->all();
            $data['teamFZR'] = PackageInitiationPlan::pieceUsername($owner_name);
            //通过id获取协助人
            $partnerIdArr = [];
            if (!empty($projectInfoData['team']['partner']) && preg_match('/,/', $projectInfoData['team']['partner'])) {
                $partnerIdArr = array_unique(explode(',', $projectInfoData['team']['partner']));
            } else if (is_string($projectInfoData['team']['partner'])) {
                $partnerIdArr = $projectInfoData['team']['partner'];
            }
            $partner_name = (new \yii\db\Query())->select('id,realname,department')->from(UserModel::tableName())->where(['in', 'id', $partnerIdArr])->all();
            $data['teamXZR'] = PackageInitiationPlan::pieceUsername($partner_name);
        } else {
            $data['teamZJ'] = [];
            $data['teamFZR'] = [];
            $data['teamXZR'] = [];
        }

        return $this->render('modal/asset-project-editing-team', ['projectid' => $data['id'], 'userChief' => $data['userChief'], 'user' => $data['user'], 'team' => $data['team'], 'teamXZR' => $data['teamXZR'], 'teamFZR' => $data['teamFZR'], 'teamZJ' => $data['teamZJ']]);
    }

    /*
     * 异步重新渲染抵押类页面
     */
    public function actionGetMortgageView()
    {
        $data['Id'] = intval(\Yii::$app->request->get('project_id', 1));          //
        $data['package_id'] = intval(\Yii::$app->request->get('package_id', 1));          //
        $data = Project::getProjectInfoData($data);
        $data['data']['res']['provinceData'] = SearchPackage::getProvinces('pid=0');
        if (!empty($data) && $data['code'] == 200) {
            $postion = intval(\Yii::$app->request->get('postion', 1));          //显示位置1
            switch ($postion) {
                case 1:
                    return $this->renderPartial('project-base-mortgage', $data['data']['res']);
                    break;
                case 2:
                    return $this->renderPartial('project-judicial-mortgage', $data['data']['res']);
                    break;
                case 3:
                    return $this->renderPartial('project-n-state-mortgage', $data['data']['res']);
                    break;
                case 4:
                    return $this->renderPartial('project-pinggu-mortgage', $data['data']['res']);
                    break;
                case 5:
                    return $this->renderPartial('project-state-mortgage', $data['data']['res']);
                    break;
                default:
                    return $this->renderPartial('project-base-mortgage', $data['data']['res']);
                    break;
            }
        }
        return false;
    }

    /*
         * 异步重新渲染抵押类页面Table(分模块加载)
         */
    public function actionGetMortgageViewTable()
    {
        $data['Id'] = intval(\Yii::$app->request->get('project_id', 1));          //
        $data['package_id'] = intval(\Yii::$app->request->get('package_id', 1));  //
        $data['mortgage_id'] = intval(\Yii::$app->request->get('mortgage_id', 1));  //
        $data['ppesid'] = intval(\Yii::$app->request->get('ppseid', 1));  //
        $dataModel = Project::getProjectInfoData($data);
        $dataModel['data']['res']['provinceData'] = SearchPackage::getProvinces('pid=0');
        $dataModel['data']['res']['ppseid'] = $data['ppesid'];
        if (!empty($dataModel) && $dataModel['code'] == 200) {
            $postion = intval(\Yii::$app->request->get('postion', 1));          //显示位置1
            switch ($postion) {
                case 1:
                    return $this->renderPartial('/project/mortgage_table/mortgage-info1', $dataModel['data']['res']);
                    break;
                case 2:
                    return $this->renderPartial('/project/mortgage_table/mortgage-state2', $dataModel['data']['res']);
                    break;
                case 3:
                    return $this->renderPartial('/project/mortgage_table/seal-state3', $dataModel['data']['res']);
                    break;
                case 4:
                    return $this->renderPartial('/project/mortgage_table/interview4', $dataModel['data']['res']);
                    break;
                case 5:
                    return $this->renderPartial('/project/mortgage_table/pinggu5', $dataModel['data']['res']);
                    break;
                default:
                    return $this->renderPartial('project-base-mortgage', $dataModel['data']['res']);
                    break;
            }
        }
        return false;
    }

    /*
       * 异步重新渲染抵押类页面Table(整个table加载)
       */
    public function actionGetMortgageViewWTable()
    {
        $data['Id'] = intval(\Yii::$app->request->get('project_id', 1));          //
        $data['package_id'] = intval(\Yii::$app->request->get('package_id', 1));  //
        $data['mortgage_id'] = intval(\Yii::$app->request->get('mortgage_id', 1));  //
        $data['ppesid'] = intval(\Yii::$app->request->get('ppesid', 1));  //
        $data = Project::getProjectInfoData($data);
        $data['data']['res']['provinceData'] = SearchPackage::getProvinces('pid=0');
        if (!empty($data) && $data['code'] == 200) {
            $data['data']['res']['ppesid'] = intval(\Yii::$app->request->get('ppesid', 1));
            return $this->renderPartial('project-state-mortgage-table', $data['data']['res']);
        }
        return false;
    }

    /*
   * 异步保存数据--抵押物情况
   */
    public function actionAjaxSaveMortgageProject()
    {
        $data['mortgage_id'] = intval(\Yii::$app->request->post('mortgage_id', 0));          //
        $data['project_id'] = intval(\Yii::$app->request->post('project_id', 1));          //
        $Pdata = \Yii::$app->request->post('data');          //项目id
        $mortgage_arr = !empty($Pdata['mortgage_arr']) ? $Pdata['mortgage_arr'] : [];  //抵押详细信息
        $mortgage_interest = !empty($Pdata['mortgage_interest']) ? $Pdata['mortgage_interest'] : [];   //抵押利息
        $mortgage_principal = !empty($Pdata['mortgage_principal']) ? $Pdata['mortgage_principal'] : [];   //抵押本金
        //统计有多少条抵押信息
        $mortgage_interest_count = count($mortgage_interest);
        $mortgage_principal_count = count($mortgage_principal);
        $newMortgageInsterArr = [];  //重组单项目基本信息
        $newMortgageUpdateArr = [];  //重组单项目基本信息

        if (empty($mortgage_arr) || $mortgage_interest_count==0 || $mortgage_principal_count==0) {
            return true;
        }

        //重新组装数据
        $mortgage_arr = array_merge($mortgage_arr);
        if ($mortgage_interest_count == $mortgage_principal_count && $mortgage_principal_count > 0) {
            for ($i = 0; $i < $mortgage_interest_count; $i++) {
                if (!empty($mortgage_arr[$i])) {
                    foreach ($mortgage_arr[$i] as $k => $v) {
                        if ($v['is_add'] == 0) {
                            $newMortgageInsterArr[$i]['mortgage_interest'] = str_replace(",","",$mortgage_interest[$i]);
                            $newMortgageInsterArr[$i]['mortgage_principal'] = str_replace(",","",$mortgage_principal[$i]);
                            $newMortgageInsterArr[$i]['mortgage_id'] = $v['mortgage_id'];
                            $newMortgageInsterArr[$i]['mortgage_info'][$k] = $v;
                        } else {
                            $newMortgageUpdateArr[$i]['mortgage_interest'] = str_replace(",","",$mortgage_interest[$i]);
                            $newMortgageUpdateArr[$i]['mortgage_principal'] = str_replace(",","",$mortgage_principal[$i]);
                            $newMortgageUpdateArr[$i]['mortgage_info'][$k] = $v;
                            $newMortgageUpdateArr[$i]['mortgage_id'] = $v['mortgage_id'];
                            $newMortgageUpdateArr[$i]['ppesid'] = $v['ppesid'];
                        }
                    }
                }
            }
        }

        //添加数据
        $params['project_id'] = $data['project_id'];

//        if (empty($newMortgageInsterArr) && empty($newMortgageUpdateArr)) {
//            return true;
//        }

        $installStateData = Project::saveMortgageBaseInfo($params, $newMortgageInsterArr);
        $updateStateData = Project::updateMortgageBaseInfo($params, $newMortgageUpdateArr);
        if ($installStateData['code'] == 200 || $updateStateData['code'] == 200) {
            //---编辑资产包-发送消息--fly---
            self::actionPostMessage($data['project_id']);
            //---编辑资产包-发送消息--fly---
            //-------添加补充说明日志------fly-start----
            $projectGroupName = '抵押物列表';
            $typeLog = 2;

            $LogsIN = $newMortgageInsterArr;
            $LogINStr = '';
            if (!empty($LogsIN) && is_array($LogsIN)) {
                foreach ($LogsIN as $k => $v) {
                    foreach ($v as $kup => $vup) {
                        if ($kup == "mortgage_interest" || $kup == "mortgage_principal") {
                            $LogINStr .= Yii::$app->params[$kup] . '：' . $vup . "\n";
                        }
                    }
                    foreach ($v['mortgage_info'] as $k1 => $v1) {
                        foreach ($v1 as $k3 => $v3) {
                            if ($k3 == "mortgage_owner" || $k3 == "mortgage_code") {
                                $LogINStr .= Yii::$app->params[$k3] . '：' . $v3 . "\n";
                            }
                            if ($k3 == "mortgage_type") {
                                $typeArr = array_filter(explode(',', $v3));
                                $mortgageTypes = Yii::$app->params['mortgageTypes3'];
                                if (!empty($typeArr) && is_array($typeArr)) {
                                    $LogINStr .= Yii::$app->params[$k3] . '：';
                                    foreach ($typeArr as $k2 => $v2) {
                                        $LogINStr .=  $mortgageTypes[$v2]['name'] . "，";
                                    }
                                    $LogINStr .= "\n";
                                }
                            }
                        }
                    }
                }
            }
            $dataInLog['project_id'] = $data['project_id'];
            $dataInLog['module'] = $projectGroupName;
            $dataInLog['type'] = $typeLog;
            $dataInLog['user_id'] = Yii::$app->user->getId();
            $dataInLog['log'] = $LogINStr;

            //----更新
            $LogsUP = $newMortgageUpdateArr;
            $LogUPStr = '';
            if (!empty($LogsUP) && is_array($LogsUP)) {
                foreach ($LogsUP as $k => $v) {
                    foreach ($v as $kup => $vup) {
                        if ($kup == "mortgage_interest" || $kup == "mortgage_principal") {
                            $LogUPStr .= Yii::$app->params[$kup] . '：' . $vup . "\n";
                        }
                    }
                    foreach ($v['mortgage_info'] as $k1 => $v1) {
                        foreach ($v1 as $k3 => $v3) {
                            if ($k3 == "mortgage_owner" || $k3 == "mortgage_code") {
                                $LogUPStr .= Yii::$app->params[$k3] . '：' . $v3 . "\n";
                            }
                            if ($k3 == "mortgage_type") {
                                $typeArr = array_filter(explode(',', $v3));
                                $mortgageTypes = Yii::$app->params['mortgageTypes3'];
                                if (!empty($typeArr) && is_array($typeArr)) {
                                    $LogUPStr .= Yii::$app->params[$k3] . '：';
                                    foreach ($typeArr as $k2 => $v2) {
                                        $LogUPStr .=  $mortgageTypes[$v2]['name'] . "，";
                                    }
                                    $LogINStr .= "\n";
                                }
                            }
                        }
                    }
                }
            }
            $dataUpLog['project_id'] = $data['project_id'];
            $dataUpLog['module'] = $projectGroupName;
            $dataUpLog['type'] = $typeLog;
            $dataUpLog['user_id'] = Yii::$app->user->getId();
            $dataUpLog['log'] = $LogUPStr;
            if (!empty($dataUpLog)) {
                if ($dataInLog['log'] != '') {
                    $dataInLog['log'] = mb_substr($dataInLog['log'], 0, -1, 'utf-8');
                    $logInState = Project::updateLog($dataInLog);
                }
                if ($dataUpLog['log'] != '') {
                    $dataUpLog['log'] = mb_substr($dataUpLog['log'], 0, -1, 'utf-8');
                    $logUpState = Project::updateLog($dataUpLog);
                }
//                if ($logInState['code'] == 200 || $logUpState['code'] == 200) {
//                    //基本信息更新数据
//                }
            }
            $tableModel = "common\models\ProjectPreEvaluationMortgage";
            $projectUnlock = ProjectLock::Unlock($tableModel,  $data['project_id'], 'project_id');
            if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                return json_encode(Responses::response200('', 1, '保存成功'));
            } else {
                return json_encode(Responses::response400($projectUnlock['message']));
            }
            //-------添加补充说明日志------fly-end----
            return true;
        }
        return false;
    }

    /*
     * 异步 抵押物基础信息
     */
    public function actionAjaxDelMortgageProject()
    {
        $params['mortgage_id'] = intval(\Yii::$app->request->post('mortgage_id', 0));          //
        $params['project_id'] = intval(\Yii::$app->request->post('project_id', 0));            //
        $params['ppes_id'] = intval(\Yii::$app->request->post('ppes_id', 0));            //
        $stateData = Project::delMortgageProject($params);
        if ($stateData['code'] == 200) {

            $projectUpdateLog = new ProjectUpdateLog();
            $module_title_array = $projectUpdateLog->getModuleArrayTitle(2);
            $projectUpdateLog->project_id = $params['project_id'];
            $projectUpdateLog->module = $module_title_array[ProjectUpdateLog::MODULE_PLEDGER_LIST];
            $projectUpdateLog->type = 2;
            $projectUpdateLog->created_at = date('Y-m-d H:i:s',time());
            $projectUpdateLog->user_id = Yii::$app->user->id;
            $projectUpdateLog->log = '删除记录';
            $projectUpdateLog->save();

            return true;
        }
        return false;
    }

    /*
     * 异步保存数据--非抵押物情况
     */
    public function actionAjaxSaveNonMortgageProject()
    {
        $data['Id'] = intval(\Yii::$app->request->post('project_id', 1));          //
        $Pdata = \Yii::$app->request->post('data');          //项目id
        $data['mortgage_other_seal_order'] = !empty($Pdata['mortgage_other_seal_order']) ? $Pdata['mortgage_other_seal_order'] : '';  //非抵押物查封顺序
        $data['mortgage_other_seal_state'] = !empty($Pdata['mortgage_other_seal_state']) ? $Pdata['mortgage_other_seal_state'] : '';   //非抵押物查封情况
        $data['bought_analysis'] = !empty($Pdata['bought_analysis']) ? $Pdata['bought_analysis'] : '';   //非抵押物的回收亮点分析
        $data['bought_reservation'] = !empty($Pdata['bought_reservation']) ? $Pdata['bought_reservation'] : '';   //非抵押部分回收（保守）
        $data['bought_radical'] = !empty($Pdata['bought_radical']) ? $Pdata['bought_radical'] : '';   //非抵押部分回收（乐观）

        $params['project_id'] = $data['Id'];
        $stateData = Project::saveProjectNonMortgage($params, $data);
        if ($stateData['code'] == 200) {
            //---编辑资产包-发送消息--fly---
            self::actionPostMessage($data['Id']);
            //---编辑资产包-发送消息--fly---
            //-------添加补充说明日志------fly-start----
            //获取项目类型
            $Logs = $stateData['data']['res'];
            $LogStr = '';
            if (!empty($Logs) && is_array($Logs)) {
                foreach ($Logs as $k => $v) {
                    if ($k != 'mortgage_id') {
                        $LogStr .= Yii::$app->params[$k] . '：' . $v . "\n";
                    }
                }
            }

            $projectUpdateLog = new ProjectUpdateLog();
            $projectUpdateLog->project_id = $data['Id'];
            $title_arr = (new ProjectUpdateLog())->getModuleArrayTitle(2);
            $projectUpdateLog->module = $title_arr[ProjectUpdateLog::MODULE_PLEDGER_NOT_VALUE_RESERVATION];
            $projectUpdateLog->type = 2;
            $projectUpdateLog->created_at = date('Y-m-d H:i:s',time());
            $projectUpdateLog->user_id = Yii::$app->user->getId();
            $projectUpdateLog-> log = $LogStr;
            $projectUpdateLog->save();

            //-------添加补充说明日志------fly-end----
            //删除锁
            $tableModel = "backend\models\ProjectPreEvaluationOtherValue";
            $projectUnlock = ProjectLock::Unlock($tableModel,   $data['Id'], 'project_id');
            if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                return json_encode(Responses::response200('', 1, '保存成功'));
            } else {
                return json_encode(Responses::response400($projectUnlock['message']));
            }
            return true;
        }
        return false;
    }

    /*
     * 异步保存数据--（抵押类项目预评估）回现评估
     */
    public function actionAjaxSavePaymentProject()
    {
        $data['Id'] = intval(\Yii::$app->request->post('project_id', 1));          //
        $Pdata = \Yii::$app->request->post('data');          //项目id
        $data['payment_reservation'] = !empty($Pdata['payment_reservation']) ? str_replace(',','',$Pdata['payment_reservation']) : '';  //回现保守
        $data['payment_radical'] = !empty($Pdata['payment_radical']) ? str_replace(',','',$Pdata['payment_radical']) : '';   //回现激进
        $data['payment_tax'] = !empty($Pdata['payment_tax']) ? str_replace(',','',$Pdata['payment_tax']) : '';   //过户税费
        $data['payment_month'] = !empty($Pdata['payment_month']) ? $Pdata['payment_month'] : '';   //回现周期（月）
        $data['payment_analysis'] = !empty($Pdata['payment_analysis']) ? $Pdata['payment_analysis'] : '';   //回现分析

        $params['project_id'] = $data['Id'];
        $stateData = Project::saveProjectPayment($params, $data);
        if ($stateData['code'] == 200) {
            //---编辑资产包-发送消息--fly---
            self::actionPostMessage($data['Id']);
            //---编辑资产包-发送消息--fly---
            //-------添加补充说明日志------fly-start----
            //获取项目类型
            $Logs = $stateData['data']['res'];
            $LogStr = '';
            if (!empty($Logs) && is_array($Logs)) {
                foreach ($Logs as $k => $v) {
                    if ($k != 'mortgage_id') {
                        $LogStr .= Yii::$app->params[$k] . '：' . $v . "\n";
                    }
                }
            }

            $projectUpdateLog = new ProjectUpdateLog();
            $projectUpdateLog->project_id = $data['Id'];
            $title_arr = (new ProjectUpdateLog())->getModuleArrayTitle(2);
            $projectUpdateLog->module = $title_arr[ProjectUpdateLog::MODULE_PLEDGER_RESERVATION];
            $projectUpdateLog->type = 2;
            $projectUpdateLog->user_id = Yii::$app->user->getId();
            $projectUpdateLog->log = $LogStr;
            $projectUpdateLog->created_at = date('Y-m-d H:i:s',time());
            $projectUpdateLog->save();

            //-------添加补充说明日志------fly-end----
            //删除锁
            $tableModel = "common\models\ProjectPaymentCollection";
            $projectUnlock = ProjectLock::Unlock($tableModel,   $data['Id'], 'project_id');
            if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                return json_encode(Responses::response200('', 1, '保存成功'));
            } else {
                return json_encode(Responses::response400($projectUnlock['message']));
            }
            return true;
        }
        return false;
    }

    /*
     * 异步保存--(抵押类)抵押物情况
     */
    public function actionAjaxSaveMortgageInfoProject()
    {
        $data['Id'] = intval(\Yii::$app->request->post('project_id', 1));
        $Pdata = \Yii::$app->request->post('data');          //项目id
        $data['mortgage_principal'] = !empty($Pdata['mortgage_principal']) ? $Pdata['mortgage_principal'] : '';  //抵押本金（万元）
        $data['mortgage_interest'] = !empty($Pdata['mortgage_interest']) ? $Pdata['mortgage_interest'] : '';  //抵押利息（万元）
        $data['mortgage_owner'] = !empty($Pdata['mortgage_owner']) ? $Pdata['mortgage_owner'] : '';  //权属人
        $data['mortgage_type'] = !empty($Pdata['mortgage_type']) ? $Pdata['mortgage_type'] : '';  //抵押物类型
        $data['mortgage_code'] = !empty($Pdata['mortgage_code']) ? $Pdata['mortgage_code'] : '';  //抵押物编号/他项权证号
        $params['project_id'] = $data['Id'];
        $stateData = Project::saveProjectMortgageData($params, $data);
        if ($stateData['code'] == 200) {
            //---编辑资产包-发送消息--fly---
            self::actionPostMessage($data['Id']);
            //---编辑资产包-发送消息--fly---
            return true;
        }
        return false;
    }

    /*
     * 异步保存--(抵押类)1.抵押物信息
     */
    public function actionAjaxSaveMortgageInfoTableProject()
    {
        $data['mortgage_id'] = intval(\Yii::$app->request->post('mortgage_id', 1));
        $Pdata = \Yii::$app->request->post('data');          //项目id
        $data['mortgage_type'] = !empty($Pdata['mortgage_type']) ? implode(',', $Pdata['mortgage_type']) : '';  //抵押物类型
        $data['mortgage_owner'] = !empty($Pdata['mortgage_owner']) ? $Pdata['mortgage_owner'] : '';  //权属人
        $data['mortgage_code'] = !empty($Pdata['mortgage_code']) ? $Pdata['mortgage_code'] : '';  //抵押物编号/他项权证号
        $data['mortgage_district'] = !empty($Pdata['mortgage_district']) ? $Pdata['mortgage_district'] : '';  //所在区域
        $data['mortgage_address'] = !empty($Pdata['mortgage_address']) ? $Pdata['mortgage_address'] : '';  //抵押物地址
        $data['mortgage_building_area'] = !empty($Pdata['mortgage_building_area']) ? $Pdata['mortgage_building_area'] : '';  //建筑面积（㎡）
        $data['mortgage_land_area'] = !empty($Pdata['mortgage_land_area']) ? $Pdata['mortgage_land_area'] : '';  //土地面积（㎡）
        $data['maximum_mortgage'] = !empty($Pdata['maximum_mortgage']) ? $Pdata['maximum_mortgage'] : '';  //最高抵押额度（元）
        $data['remaining_service_life'] = !empty($Pdata['remaining_service_life']) ? $Pdata['remaining_service_life'] : '';  //剩余使用年限
        $data['ppseid'] = !empty($Pdata['ppseid']) ? $Pdata['ppseid'] : '';  //抵押物详情id
        $params['ppseid'] = $data['ppseid'];
        $stateData = Project::SaveMortgageInfoTable($params, $data);
        if ($stateData['code'] == 200) {
            //获取项目id
            $projectModel = (new \yii\db\Query())->from("project_pre_evaluation_seal as ppes")->leftJoin("project_pre_evaluation_mortgage as ppem", 'ppem.id=ppes.mortgage_id')->where(['=', 'ppes.id', $data['ppseid']])->one();
            $project_id = 0;
            if (!empty($projectModel['project_id'])) {
                $project_id = $projectModel['project_id'];
            }
            //---编辑资产包-发送消息--fly---
            self::actionPostMessage($project_id);
            //---编辑资产包-发送消息--fly---

            //抵押物列表--1.抵押物信息
            $tableModel = "backend\models\ProjectPreEvaluationSeal";
            $projectUnlock = ProjectLock::Unlock($tableModel, $params['ppseid'] , 'id');
            if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                return json_encode(Responses::response200('', 1, '保存成功'));
            } else {
                return json_encode(Responses::response400($projectUnlock['message']));
            }
            return true;
        }
        return false;
    }

    /*
 * 异步保存--(抵押类)2.抵押情况
 */
    public function actionAjaxSaveMortgageConditionTableProject()
    {
        $data['mortgage_id'] = intval(\Yii::$app->request->post('mortgage_id', 1));
        $Pdata = \Yii::$app->request->post('data');          //项目id
        $data['mortgage_order'] = !empty($Pdata['mortgage_order']) ? $Pdata['mortgage_order'] : '';  //抵押物抵押顺序
        $data['is_first_mortgage'] = !empty($Pdata['is_first_mortgage']) ? $Pdata['is_first_mortgage'] : 1;  //是否首押
        $data['mortgage_future'] = !empty($Pdata['mortgage_future']) ? $Pdata['mortgage_future'] : '';  //后续抵押情况
        $data['mortgage_situation'] = !empty($Pdata['mortgage_situation']) ? $Pdata['mortgage_situation'] : '';  //抵押情况描述
        $data['ppseid'] = !empty($Pdata['ppseid']) ? $Pdata['ppseid'] : '';  //抵押物详情id
        $params['ppseid'] = $data['ppseid'];
        $stateData = Project::SaveMortgageConditionTable($params, $data);
        if ($stateData['code'] == 200) {
            //获取项目id
            $projectModel = (new \yii\db\Query())->from("project_pre_evaluation_seal as ppes")->leftJoin("project_pre_evaluation_mortgage as ppem", 'ppem.id=ppes.mortgage_id')->where(['=', 'ppes.id', $data['ppseid']])->one();
            $project_id = 0;
            if (!empty($projectModel['project_id'])) {
                $project_id = $projectModel['project_id'];
            }
            //---编辑资产包-发送消息--fly---
            self::actionPostMessage($project_id);
            //---编辑资产包-发送消息--fly---

            //抵押物列表--2.抵押情况
            $tableModel = "backend\models\ProjectPreEvaluationSeal";
            $projectUnlock = ProjectLock::Unlock($tableModel, $params['ppseid'] , 'id');
            if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                return json_encode(Responses::response200('', 1, '保存成功'));
            } else {
                return json_encode(Responses::response400($projectUnlock['message']));
            }
            return true;
        }
        return false;
    }

    /*
* 异步保存--(抵押类)3.查封情况
*/
    public function actionAjaxSaveMortgageSealTableProject()
    {
        $data['mortgage_id'] = intval(\Yii::$app->request->post('mortgage_id', 1));
        $Pdata = \Yii::$app->request->post('data');          //项目id
        $data['mortgage_seal_order'] = !empty($Pdata['mortgage_seal_order']) ? $Pdata['mortgage_seal_order'] : '';  //抵押物抵押顺序
        $data['is_first_seal'] = !empty($Pdata['is_first_seal']) ? $Pdata['is_first_seal'] : 1;  //是否首封
        $data['whether_exploration'] = !empty($Pdata['whether_exploration']) ? $Pdata['whether_exploration'] : 1;  //是否详勘
        $data['mortgage_seal_state'] = !empty($Pdata['mortgage_seal_state']) ? $Pdata['mortgage_seal_state'] : '';  //抵押物查封情况
        $data['ppseid'] = !empty($Pdata['ppseid']) ? $Pdata['ppseid'] : '';  //抵押物详情id
        $params['ppseid'] = $data['ppseid'];
        $stateData = Project::SaveMortgageSealTable($params, $data);
        if ($stateData['code'] == 200) {
            //获取项目id
            $projectModel = (new \yii\db\Query())->from("project_pre_evaluation_seal as ppes")->leftJoin("project_pre_evaluation_mortgage as ppem", 'ppem.id=ppes.mortgage_id')->where(['=', 'ppes.id', $data['ppseid']])->one();
            $project_id = 0;
            if (!empty($projectModel['project_id'])) {
                $project_id = $projectModel['project_id'];
            }
            //---编辑资产包-发送消息--fly---
            self::actionPostMessage($project_id);
            //---编辑资产包-发送消息--fly---

            //抵押物列表--3.查封情况
            $tableModel = "backend\models\ProjectPreEvaluationSeal";
            $projectUnlock = ProjectLock::Unlock($tableModel, $params['ppseid'] , 'id');
            if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                return json_encode(Responses::response200('', 1, '保存成功'));
            } else {
                return json_encode(Responses::response400($projectUnlock['message']));
            }
            return true;
        }
        return false;
    }

    /*
    * 异步保存--(抵押类)4.现场访谈
    */
    public function actionAjaxSaveMortgageInterviewTableProject()
    {
        $data['mortgage_id'] = intval(\Yii::$app->request->post('mortgage_id', 1));
        $Pdata = \Yii::$app->request->post('data');          //项目id
        $data['building_title'] = !empty($Pdata['building_title']) ? $Pdata['building_title'] : '';  //楼盘名称 project_pre_evaluation_interview
        $data['finished_date'] = !empty($Pdata['finished_date']) ? $Pdata['finished_date'] : '';  //建成日期
        $data['total_floor'] = !empty($Pdata['total_floor']) ? $Pdata['total_floor'] : '';  //总层数
        $data['which_floor'] = !empty($Pdata['which_floor']) ? $Pdata['which_floor'] : '';  //所在层数
        $data['surroundings'] = !empty($Pdata['surroundings']) ? $Pdata['surroundings'] : '';  //区位描述/周边氛围
        $data['property'] = !empty($Pdata['property']) ? $Pdata['property'] : '';  //物业通达性
        $data['property_state'] = !empty($Pdata['property_state']) ? $Pdata['property_state'] : '';  //物业维护状况
        $data['whether_work'] = !empty($Pdata['whether_work']) ? $Pdata['whether_work'] : 0;  //目前状态
        $data['lease_info'] = !empty($Pdata['lease_info']) ? $Pdata['lease_info'] : '';  //租赁/租赁时间/租金缴纳
        $data['is_only'] = !empty($Pdata['is_only']) ? $Pdata['is_only'] : '';  //是否业主唯一住房
        $data['willing'] = !empty($Pdata['willing']) ? $Pdata['willing'] : '';  //业主还款意愿
        $data['market_price'] = !empty($Pdata['market_price']) ? $Pdata['market_price'] : '';  //市场走访价格（售价/套）
        $data['market_rent_price'] = !empty($Pdata['market_rent_price']) ? $Pdata['market_rent_price'] : '';  //市场走访租金
        $data['comparison_property1'] = !empty($Pdata['comparison_property1']) ? $Pdata['comparison_property1'] : '';  //可比物业1
        $data['comparison_property2'] = !empty($Pdata['comparison_property2']) ? $Pdata['comparison_property2'] : '';  //可比物业2
        $data['comparison_property3'] = !empty($Pdata['comparison_property3']) ? $Pdata['comparison_property3'] : '';  //可比物业3
        $data['comparison_property4'] = !empty($Pdata['comparison_property4']) ? $Pdata['comparison_property4'] : '';  //可比物业4
        $data['info_origin'] = !empty($Pdata['info_origin']) ? $Pdata['info_origin'] : '';  //走访信息来源
        $data['contact'] = !empty($Pdata['contact']) ? $Pdata['contact'] : '';  //联系方式
        $data['remark'] = !empty($Pdata['remark']) ? $Pdata['remark'] : '';  //备注说明
        $data['ppesid'] = !empty($Pdata['ppseid']) ? $Pdata['ppseid'] : '';  //抵押物详情id
        $params['ppesid'] = $data['ppesid'];
        $stateData = Project::SaveMortgageInterviewTable($params, $data);
        if ($stateData['code'] == 200) {
            //获取项目id
            $projectModel = (new \yii\db\Query())->from("project_pre_evaluation_seal as ppes")->leftJoin("project_pre_evaluation_mortgage as ppem", 'ppem.id=ppes.mortgage_id')->where(['=', 'ppes.id', $data['ppesid']])->one();
            $project_id = 0;
            if (!empty($projectModel['project_id'])) {
                $project_id = $projectModel['project_id'];
            }
            //---编辑资产包-发送消息--fly---
            self::actionPostMessage($project_id);
            //---编辑资产包-发送消息--fly---

            //抵押物列表--4.现场访谈
            $tableModel = "backend\models\ProjectPreEvaluationInterview";
            $projectUnlock = ProjectLock::Unlock($tableModel, $params['ppesid'] , 'id');
            if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                return json_encode(Responses::response200('', 1, '保存成功'));
            } else {
                return json_encode(Responses::response400($projectUnlock['message']));
            }

            return true;
        }
        return false;
    }

    /*
* 异步保存--(抵押类)5.定价评估 project_pre_evaluation_value
*/
    public function actionAjaxSaveEvaluationValueTableProject()
    {
        $data['mortgage_id'] = intval(\Yii::$app->request->post('mortgage_id', 1));
        $Pdata = \Yii::$app->request->post('data');          //项目id
        $data['bank_value'] = !empty($Pdata['bank_value']) ? $Pdata['bank_value'] : '';  //银行评估价值总价
        $data['third_partner_value'] = !empty($Pdata['third_partner_value']) ? $Pdata['third_partner_value'] : '';  //第三方评估价（总价/元）
        $data['third_partner_value_other'] = !empty($Pdata['third_partner_value_other']) ? $Pdata['third_partner_value_other'] : '';  //第三方评估价（清算价值/元）
        $data['auction_price'] = !empty($Pdata['auction_price']) ? $Pdata['auction_price'] : '';  //司法拍卖单价（元/㎡）
        $data['market_conserve_price'] = !empty($Pdata['market_conserve_price']) ? $Pdata['market_conserve_price'] : '';  //市场保守单价（元/㎡）
        $data['market_radical_price'] = !empty($Pdata['market_radical_price']) ? $Pdata['market_radical_price'] : '';  //市场激进单价（元/㎡）
        $data['market_conservation_total_price'] = !empty($Pdata['market_conservation_total_price']) ? $Pdata['market_conservation_total_price'] : '';  //市场保守总价（元）
        $data['market_radical_total_price'] = !empty($Pdata['market_radical_total_price']) ? $Pdata['market_radical_total_price'] : 0;  //市场激进总价（元）
        $data['payment_reservation'] = !empty($Pdata['payment_reservation']) ? $Pdata['payment_reservation'] : '';  //抵押物变现价保守（元）
        $data['payment_radical'] = !empty($Pdata['payment_radical']) ? $Pdata['payment_radical'] : '';  //抵押物变现价激进（元）
        $data['price_reason'] = !empty($Pdata['price_reason']) ? $Pdata['price_reason'] : '';  //抵押物定价依据
        $data['ppesid'] = !empty($Pdata['ppseid']) ? $Pdata['ppseid'] : '';  //抵押物详情id
        $params['ppesid'] = $data['ppesid'];
        $stateData = Project::SaveEvaluationValueTable($params, $data);
        if ($stateData['code'] == 200) {
            //获取项目id
            $projectModel = (new \yii\db\Query())->from("project_pre_evaluation_seal as ppes")->leftJoin("project_pre_evaluation_mortgage as ppem", 'ppem.id=ppes.mortgage_id')->where(['=', 'ppes.id', $data['ppesid']])->one();
            $project_id = 0;
            if (!empty($projectModel['project_id'])) {
                $project_id = $projectModel['project_id'];
            }
            //---编辑资产包-发送消息--fly---
            self::actionPostMessage($project_id);
            //---编辑资产包-发送消息--fly---

            //抵押物列表--5.定价评估
            $tableModel = "backend\models\ProjectPreEvaluationValue";
            $projectUnlock = ProjectLock::Unlock($tableModel, $params['ppesid'] , 'ppes');
            if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                return json_encode(Responses::response200('', 1, '保存成功'));
            } else {
                return json_encode(Responses::response400($projectUnlock['message']));
            }
            return true;
        }
        return false;
    }

    /**
     *  统一解锁
     */
    public static function actionAjaxUnLock()
    {
        $postion = Yii::$app->request->post('postion', 0);
        $project_id = Yii::$app->request->post('project_id', 0);
        $ppesid = Yii::$app->request->post('ppesid', 0);

        switch ($postion) {
            case 2:
                $tableModel = "common\models\Project";
                $projectUnlock = ProjectLock::Unlock($tableModel, $project_id, 'id');
                if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                    return json_encode(Responses::response200('', 1, '保存成功'));
                } else {
                    return json_encode(Responses::response400($projectUnlock['message']));
                }
                break;
            case 4:
                $tableModel = "common\models\ProjectPreEvaluationLawsuit";
                $projectUnlock = ProjectLock::Unlock($tableModel, $project_id, 'project_id');
                if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                    return json_encode(Responses::response200('', 1, '保存成功'));
                } else {
                    return json_encode(Responses::response400($projectUnlock['message']));
                }
                break;
            case 6:
                $tableModel = "common\models\ProjectPreEvaluationValueEvaluation";
                $projectUnlock = ProjectLock::Unlock($tableModel, $project_id, 'project_id');
                if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                    return json_encode(Responses::response200('', 1, '保存成功'));
                } else {
                    return json_encode(Responses::response400($projectUnlock['message']));
                }
                break;
            case 8:
                $tableModel = "common\models\ProjectPreEvaluationOtherNote";
                $projectUnlock = ProjectLock::Unlock($tableModel, $project_id, 'project_id');
                if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                    return json_encode(Responses::response200('', 1, '保存成功'));
                } else {
                    return json_encode(Responses::response400($projectUnlock['message']));
                }
                break;
            case 10:
                $tableModel = "common\models\ProjectTransfer";
                $projectUnlock = ProjectLock::Unlock($tableModel, $project_id, 'project_id');
                if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                    return json_encode(Responses::response200('', 1, '保存成功'));
                } else {
                    return json_encode(Responses::response400($projectUnlock['message']));
                }
                break;
            case 12:
                $tableModel = "backend\models\ProjectTransferHistory";
                $projectUnlock = ProjectLock::Unlock($tableModel, $project_id, 'project_id');
                if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                    return json_encode(Responses::response200('', 1, '保存成功'));
                } else {
                    return json_encode(Responses::response400($projectUnlock['message']));
                }
                break;
            case 14:
                $tableModel = "common\models\ProjectTeam";
                $projectUnlock = ProjectLock::Unlock($tableModel, $project_id, 'project_id');
                if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                    return json_encode(Responses::response200('', 1, '保存成功'));
                } else {
                    return json_encode(Responses::response400($projectUnlock['message']));
                }
                break;

            //抵押类解锁
            case 15:
                //抵押物列表
                $tableModel = "common\models\ProjectPreEvaluationMortgage";
                $projectUnlock = ProjectLock::Unlock($tableModel, $project_id, 'project_id');
                if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                    return json_encode(Responses::response200('', 1, '保存成功'));
                } else {
                    return json_encode(Responses::response400($projectUnlock['message']));
                }
                break;
            case 111:
                //抵押物列表--1.抵押物信息2.3.
                $tableModel = "backend\models\ProjectPreEvaluationSeal";
                $projectUnlock = ProjectLock::Unlock($tableModel, $ppesid, 'id');
                if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                    return json_encode(Responses::response200('', 1, '保存成功'));
                } else {
                    return json_encode(Responses::response400($projectUnlock['message']));
                }
                break;
            case 114:
                //抵押物列表--4.现场访谈
                $tableModel = "backend\models\ProjectPreEvaluationInterview";
                $projectUnlock = ProjectLock::Unlock($tableModel, $ppesid, 'id');
                if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                    return json_encode(Responses::response200('', 1, '保存成功'));
                } else {
                    return json_encode(Responses::response400($projectUnlock['message']));
                }
                break;
            case 115:
                //抵押物列表--5.定价评估
                $tableModel = "backend\models\ProjectPreEvaluationValue";
                $projectUnlock = ProjectLock::Unlock($tableModel,$ppesid , 'ppes');
                if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                    return json_encode(Responses::response200('', 1, '保存成功'));
                } else {
                    return json_encode(Responses::response400($projectUnlock['message']));
                }
                break;
            case 21:
                //抵押物--非抵押物情况
                $tableModel = "backend\models\ProjectPreEvaluationOtherValue";
                $projectUnlock = ProjectLock::Unlock($tableModel,  $project_id, 'project_id');
                if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                    return json_encode(Responses::response200('', 1, '保存成功'));
                } else {
                    return json_encode(Responses::response400($projectUnlock['message']));
                }
                break;
            case 22:
                //抵押物--回现评估
                $tableModel = "common\models\ProjectPaymentCollection";
                $projectUnlock = ProjectLock::Unlock($tableModel,  $project_id, 'project_id');
                if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                    return json_encode(Responses::response200('', 1, '保存成功'));
                } else {
                    return json_encode(Responses::response400($projectUnlock['message']));
                }
                break;
            //抵押类解锁
            default:
                $tableModel = "common\models\Project";
                $projectUnlock = ProjectLock::Unlock($tableModel, $project_id, 'id');
                if (!empty($projectUnlock) && $projectUnlock['code'] == 200) {
                    return json_encode(Responses::response200('', 1, '保存成功'));
                } else {
                    return json_encode(Responses::response400($projectUnlock['message']));
                }
                break;
        }
    }


    /**
     * 项目审批反馈
     * @return string
     */
    public function actionAccessAudit()
    {
        $packageId = (int)Yii::$app->request->get('package_id');
        $projectId = (int)Yii::$app->request->get('project_id');

        /**--------------------------  头部信息start --------------------------------**/
        //项目详情
        $project = Project::findOne($projectId);

        $data['Id'] = $projectId;
        $data['package_id'] = $packageId;
        $data['mortgage_id'] = intval(\Yii::$app->request->get('mortgage_id', 1));
        $data = Project::getProjectInfoData($data);
        //$data['data']['res']['provinceData'] = SearchPackage::getProvinces('pid=0');
        //所有部门人员
        $userModel = new UserModel();
//        $where = ['not in', 'department',
//            ['总裁办', '风控管理中心', '财务部', '技术部', '品牌部', '新大唐学院', '人力行政部',
//                'ceooffice', 'windControlManagementCenter', 'finance', 'technology', 'brand', 'college', 'humanAdministration','',
//            ]];
        $where = ['in','department',['project1','project2','project3','project6','foreignAffairsOffice']];
        $data['data']['res']['Base']['departments'] = $userModel->getDepartmentUsers($where);
        $data['data']['res']['Base']['access_users_ids'] = $data['data']['res']['Base']['access_users'] != "" ? explode(",", $data['data']['res']['Base']['access_users']) : "";
        $data['data']['res']['Base']['access_users'] = $this->getAccessUsers($data['data']['res']['Base']['access'], $data['data']['res']['Base']['access']);

        $data['user'] = (new \yii\db\Query())->select('*')->from('user')->all();
        $data['userChief'] = (new \yii\db\Query())->select('*')->from('user')->andWhere(['=', 'is_leader', 1])->all();

        $data['team'] = (new \yii\db\Query())->from(ProjectTeam::tableName())->select('*')->where(['=', 'project_id', $projectId])->one();
        if (!empty($projectInfoData['team'])) {
            //通过id获取总监名称
            $leaderIdArr = [];
            if (!empty($projectInfoData['team']['manager']) && preg_match('/,/', $projectInfoData['team']['manager'])) {
                $leaderIdArr = array_unique(explode(',', $projectInfoData['team']['manager']));
            } else if (is_string($projectInfoData['team']['manager'])) {
                $leaderIdArr = $projectInfoData['team']['manager'];
            }
            $leader_name = (new \yii\db\Query())->select('id,realname,department')->from(UserModel::tableName())->where(['in', 'id', $leaderIdArr])->all();
            $data['teamZJ'] = PackageInitiationPlan::pieceUsername($leader_name);
            //通过id获取负责人名称
            $ownerIdArr = [];
            if (!empty($projectInfoData['team']['owner']) && preg_match('/,/', $projectInfoData['team']['owner'])) {
                $ownerIdArr = array_unique(explode(',', $projectInfoData['team']['owner']));
            } else if (is_string($projectInfoData['team']['owner'])) {
                $ownerIdArr = $projectInfoData['team']['owner'];
            }
            $owner_name = (new \yii\db\Query())->select('id,realname,department')->from(UserModel::tableName())->where(['in', 'id', $ownerIdArr])->all();
            $data['teamFZR'] = PackageInitiationPlan::pieceUsername($owner_name);
            //通过id获取协助人
            $partnerIdArr = [];
            if (!empty($projectInfoData['team']['partner']) && preg_match('/,/', $projectInfoData['team']['partner'])) {
                $partnerIdArr = array_unique(explode(',', $projectInfoData['team']['partner']));
            } else if (is_string($projectInfoData['team']['partner'])) {
                $partnerIdArr = $projectInfoData['team']['partner'];
            }
            $partner_name = (new \yii\db\Query())->select('id,realname,department')->from(UserModel::tableName())->where(['in', 'id', $partnerIdArr])->all();
            $data['teamXZR'] = PackageInitiationPlan::pieceUsername($partner_name);
        } else {
            $data['teamZJ'] = [];
            $data['teamFZR'] = [];
            $data['teamXZR'] = [];
        }

        //是否关注
        $data_like = ProjectLike::find()->where(['project_id' => $data['data']['res']['Base']['id'], 'type' => 1, 'user_id' => Yii::$app->user->id])->asArray()->one();
        if ($data_like['id']) {
            $data['data']['res']['Base']['flow'] = 1;
        } else {
            $data['data']['res']['Base']['flow'] = 0;
        }
        //是否亮点
        $data_like = ProjectLike::find()->where(['project_id' => $data['data']['res']['Base']['id'], 'type' => 2, ])->asArray()->one();
        if ($data_like['id']) {
            $data['data']['res']['Base']['light_spot'] = 1;
        } else {
            $data['data']['res']['Base']['light_spot'] = 0;
        }
        //获取配置团队成员信息
        $teamZJ = array_column($data['data']['res']['teamZJ'], 'id');
        $teamFZR = array_column($data['data']['res']['teamFZR'], 'id');
        $teamXZR = array_column($data['data']['res']['teamXZR'], 'id');

//        $teamS = array_merge($teamZJ, $teamFZR, $teamXZR);
//        $data['data']['res']['teamInfo'] = Project::getTeamUserData($teamS);

        $data['data']['res']['teamInfo']['teamZJ'] = array();
        $data['data']['res']['teamInfo']['teamFZR'] = array();
        $data['data']['res']['teamInfo']['teamXZR'] = array();
        $getDepartmentUsersList = (new UserModel())->getDepartmentUsersList();

        if (!empty($teamZJ)) {
            foreach ($teamZJ as $value) {
                if (isset($getDepartmentUsersList[$value])) {
                    $teamZJ_array['id'] = $getDepartmentUsersList[$value]['id'];
                    $teamZJ_array['realname'] = $getDepartmentUsersList[$value]['realname'];
                    $teamZJ_array['username'] = $getDepartmentUsersList[$value]['username'];
                    $teamZJ_array['department'] = $getDepartmentUsersList[$value]['description'];
                    $teamZJ_array['avatar'] = $getDepartmentUsersList[$value]['avatar'];
                    $teamZJ_array['role'] = '项目总监';
                    $data['data']['res']['teamInfo']['teamZJ'][] = $teamZJ_array;
                }
            }
        }

        if (!empty($teamFZR)) {
            foreach ($teamFZR as $value) {
                if (isset($getDepartmentUsersList[$value])) {
                    $teamFZR_array['id'] = $getDepartmentUsersList[$value]['id'];
                    $teamFZR_array['realname'] = $getDepartmentUsersList[$value]['realname'];
                    $teamFZR_array['username'] = $getDepartmentUsersList[$value]['username'];
                    $teamFZR_array['department'] = $getDepartmentUsersList[$value]['description'];
                    $teamFZR_array['avatar'] = $getDepartmentUsersList[$value]['avatar'];
                    $teamFZR_array['role'] = '项目经理';
                    $data['data']['res']['teamInfo']['teamFZR'][] = $teamFZR_array;
                }
            }
        }

        if (!empty($teamXZR)) {
            foreach ($teamXZR as $value) {
                if (isset($getDepartmentUsersList[$value])) {
                    $teamXZR_array['id'] = $getDepartmentUsersList[$value]['id'];
                    $teamXZR_array['realname'] = $getDepartmentUsersList[$value]['realname'];
                    $teamXZR_array['username'] = $getDepartmentUsersList[$value]['username'];
                    $teamXZR_array['department'] = $getDepartmentUsersList[$value]['description'];
                    $teamXZR_array['avatar'] = $getDepartmentUsersList[$value]['avatar'];
                    $teamXZR_array['role'] = '团队成员';
                    $data['data']['res']['teamInfo']['teamXZR'][] = $teamXZR_array;
                }
            }
        }

        //项目所属资产包
        $packageInfo = Package::findOne($packageId);

        if (!empty($packageInfo)) {
            $data['data']['res']['packageName'] = $packageInfo->title;
            $data['data']['res']['Base']['code'] = $packageInfo->code;
            $province = '';
            $city = '';
            $country = new \common\models\Country();
            if ($packageInfo->province > 0) {
                $province = $country->getName($packageInfo->province);
            }
            if ($packageInfo->city > 0) {
                $city = $country->getName($packageInfo->city);
            }
            $data['data']['res']['Base']['country'] = $province . $city;
        } else {
            $data['data']['res']['packageName'] = '';
            $data['data']['res']['Base']['code'] = '';
            $data['data']['res']['Base']['country'] = '';
        }
        /**--------------------------  头部信息end --------------------------------**/

        $list = (new \yii\db\Query())->select('*,ar.id as result_id')->from('package_application as pa')
            ->leftJoin('application_result as ar', 'pa.id = ar.application_id')
            ->leftJoin('package as p', 'pa.package_id = p.id')
            //->where(['pa.package_id'=>$projectId, 'pa.workflow_status'=>2, 'pa.is_package'=>2, 'pa.type'=>5 ]) 已审批
            ->where(['pa.package_id' => $projectId, 'pa.is_package' => 2, 'pa.type' => 5])
            ->all();

        if (!empty($list) && is_array($list)) {
            $userModel = new UserModel();
            $userList = $userModel->getDepartmentUsersList();
            foreach ($list as $key => $value) {
                $list[$key]['applied_at'] = date('Y/m/d H:i', strtotime($value['applied_at']));
                //$list[$key]['proposer'] = $userList[$value['proposer']]['description'] . '——' . $userList[$value['proposer']]['realname'];
                //$list[$key]['user_id'] = $userList[$value['user_id']]['description'] . '——' . $userList[$value['user_id']]['realname'];
                $list[$key]['proposer'] = $userList[$value['proposer']]['realname'];
                $list[$key]['user_id'] = $userList[$value['user_id']]['realname'];
                $list[$key]['reviewed_at'] = date('Y/m/d H:i:s', strtotime($value['reviewed_at']));
                switch ($value['result']) {
                    case 1:
                        $list[$key]['result'] = '未审核';
                        break;
                    case 2:
                        $list[$key]['result'] = '通过';
                        break;
                    case 3:
                        $list[$key]['result'] = '未通过';
                        break;
                    default;
                }
            }
        }

        return $this->render('access-audit', ['list' => $list, 'topData' => $data['data']['res'], 'data' => $data, 'projectModel' => $project,
            'packageId' => $packageId, 'projectId' => $projectId]);
    }

    public static function actionPostMessage($project_id)
    {
        //----编辑项目发送消息---------------------
//        $package_id         = !empty($teamMembersData['package_id'])?intval($teamMembersData['package_id']):0;
        //根据package_id获取标题
        $pack_name = (new \yii\db\Query())->from(Project::tableName())->where(['=', 'id', $project_id])->one();
        //根据package_id获取状态
        $appStates = (new \yii\db\Query())->select('status')->from(Project::tableName())->where(['=', 'id', $project_id])->one();
        $appStateName = $appStates['status']>=4?\Yii::$app->params['projectState'][$appStates['status']]:"";//当前状态
        //最后一次更新人员
        $sender_id = \Yii::$app->user->getId();
        $userName = (new \Yii\db\Query())->from(User::tableName())->leftJoin('auth_item as ai', 'ai.name = user.department')->where(['=', 'id', $sender_id])->one();
        $message = [
            'pack_name' => $pack_name,
            'appStates' => $appStateName,
            'lastUpdateUser' => $userName['realname'],
            'lastUpdateUserBumen' => $userName['description'],
        ];
        //发送给关注此资产包的用户
        $user_id = (new \yii\db\Query())->from('project_like')->select('user_id')->where(['=', 'type', 1])->andWhere(['=', 'project_id', $project_id])->all();
        $user_id = array_column($user_id, 'user_id');

        if (!empty($user_id) && is_array($user_id)) {
            //如果关注的用户中有自己（编辑用户），则从发送的消息人中删除 2018年3月5日14:52:06 von
            if (in_array($sender_id,$user_id)){
                foreach ($user_id as $ku => $vu) {
                    if ($vu==$sender_id){
                        unset($user_id[$ku]);
                    }
                }
            }
        }
        if (!empty($user_id) && is_array($user_id)) {
            $data = [];
            $data['sender'] = \Yii::$app->user->getId();//发件人id
            $data['package_project_id'] = $project_id;//资产包id
            $data['is_package'] = 2;//是否是资产包/1是资产包/2是项目
            $data['message_val'] = json_encode($message); //消息内容 json

            $data['user_id'] = $user_id;//收件人id
            $data['message_state'] = \Yii::$app->params['UNREND'];//消息状态 0未阅读 1已阅读
            $data['message_group'] = \Yii::$app->params['GUANZHU_UP']; //消息分类 1待审批提醒 2审批反馈 3关注更新*/

            $param = [];
            $param['where_sender'] = \Yii::$app->user->getId();//发件人id
            $param['where_is_package'] = 1;//是否是资产包/1是资产包/2是项目
            $param['where_package_project_id'] = $project_id;//资产包id
            $param['where_message_group'] = \Yii::$app->params['GUANZHU_UP'];//资产包id 消息分类 1待审批提醒 2审批反馈 3关注更新
            $param['is_guanzhu'] = 1; //如果是关注，则先删除message_user_group表的信息在添加
            $savePackageMessage = \common\models\InstationMessage::saveMessage($param, $data);
        } else {
            $savePackageMessage['code'] = 200;
            $savePackageMessage['message'] = '编辑成功,无关注用户,没发送消息';
        }
        return $savePackageMessage;
    }
}